c++heap-memoryraiitry-finally

How to ensure (like a try-finally) destruction of a HEAP-ALLOCATED object


I'm looking for a way to ensure that an object that is executed on the heap is ALWAYS deallocated when I'm done with it.

I know that if it's allocated on the stack, I can use RAII to ensure it will be taken care of - unfortunately, this won't work for me (at least directly) because the object in question is actually created by calling an api function, which then returns a pointer to the object it creates on the heap.

So, conceptually, what I want to do is something like:

TheApi::ApiObject* p_myObj = TheApi::createAnApiObj();
try
{
    doStuffWithMyObjThatMayError(p_myObj);
}
finally
{
    delete p_myObj;
}

The only thing I can think of to do would be to make some sort of dummy cleanup class, and create an instance of that on the stack:

class MegaMaid
{
private:
    TheApi::ApiObject* toFree;
public:
    MegaMaid(TheApi::ApiObject* toFree)
    {
        this->toFree = toFree;
    }

    ~MegaMaid()
    {
        delete toFree;
    }
};

void doStuff()
{
    TheApi::ApiObject* p_myObj = TheApi::createAnApiObj();
    TheApi::ApiObject* p_myObj;
    MegaMaid cleaner(p_myObj);
    doStuffWithMyObjThatMayError(p_myObj);
}

Is there a better way to accomplish this? Or is this the accepted solution?


Solution

  • You can still use RAII on pointers returned by functions. You can use smart pointers (which is exactly what the dummy class you are describing is) like this:

    std::unique_ptr<TheApi::ApiObject> p_myObj(TheApi::createAnApiObj());