C++ : handle resources if constructors may throw exceptions (Reference to FAQ 17.4]

There is a similar question here that covers what your asking.

In this case, if the call to new fails, then the memory for the pointer is guaranteed to be freed. If the call succeeds, and the constructor throws after that, you will have a memory leak.

The destructor of the class will not be called, because the object was never fully constructed. There are two ways to fix this.

1)

Have exceptions fully managed in the constructor:

class Foo
{
public:
    Foo()
    try
    {
        p = new p;

        throw /* something */; 
    }
    catch (...)
    {
       delete p;

       throw; //rethrow. no memory leak
    }
private:
    int *p;
};

2)

Or use a smart pointer. When a constructor is entered, all of its members have been constructed. And because when a constructor throws, and objects members have been constructed, they must be destructed. And a smart pointer fixes that:

class Foo
{
public:
    Foo() :
    p(new int)
    {
        throw /* something */; 
    }
private:
    std::auto_ptr<int> p;
};

Leave a Comment