c++raiiscopeguard

ScopeGuard usage with multiple resourace allocatons and exit points in a fucntion


I have multiple resources allocated in a function, therefore quite a few pointers and out of which I have to return one pointer (let's say ret_ptr) and deallocate others (all othr_ptrs) before leaving the function.

I have multiple exit points in this function (where ret_ptr is 0 or it is pointing to a valid memory or an exception). Therefore before all the return statements and in the exception(catch block) I have to delete the othr_ptrs (doing multiple times in the function). Is there any way with "ScopeGuards" I could reduce the multiple clean-ups ?

X* func()
{
    try

    {
        A* a = new ..;
        B* b = new ..;


        if (something)
        {
            delete a;
            delete b;
            return 0;  // return NULL ptr  
        }

        X* x = new ..;
    }
    catch(...)
    {
        delete a;
        delete b;
        return x; 
    }

    delete a;
    delete b;
    return x; 
}

Solution

  • You may use std::unique_ptr (C++11), your example becomes something like:

    std::unique_ptr<X> func()
    {
        std::unique_ptr<X> x;
        try
        {
            std::unique_ptr<A> a(new A);
            std::unique_ptr<B> b(new B);
    
            if (something)
            {
                return nullptr;
            }
            x.reset(new X);
        }
        catch (...)
        {
            return std::move(x);
        }
        return std::move(x);
    }