Question

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?

Was it helpful?

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());

OTHER TIPS

That "dummy class" is known as "smart pointer". You should check out std::auto_ptr or boost::shared_ptr. They provide exactly what you look for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top