Search code examples
c++smart-pointersraii

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.


Solution

  • 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);
    }