简体   繁体   中英

Use RAII with factory taking as input a reference to pointer

I have a function which construct an object, and it takes as input a reference to pointer:

void generator(Object*&)

and I call it as:

Object* obj = nullptr;
generator(obj);

...
use obj
...
delete obj;

As you can see the user is responsible for the destruction of obj . Is there a better way to use smart pointers or other solution to avoid to manual memory management?

I cannot change the generator function.

Even if you can't modify generator :(, you can still use smart pointer:

Object* obj = nullptr;
generator(obj);
std::unique_ptr<Object> raii_obj(obj);
...
use obj/raii_obj
...
// auto delete raii_obj.

And you can even wrap it in a function:

std::unique_ptr<Object> make_object()
{
    Object* obj = nullptr;
    generator(obj);
    return std::unique_ptr<Object>(obj);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM