Yes, it's possible if new
throws in the constructor.
The destructor would then not be run and any allocations that had already happened will not be released.
To be more specific: if any memory has been dynamically allocated before an exception occurs in the constructor, a memory leak will occur because the destructor of the object will not run.
A simple illustration:
class Leaks
{
private:
data* d;
public:
Leaks()
{
data = new int;
throw 1;
}
~Leaks()
{
delete data;
}
};
This is a flawed design. data
will always leak here. There's nothing you can do about it. (The only case in which data wouldn't leak would be if the new
failed.)
Since new
itself can throw, your example code is capable of throwing after one or more allocations, thus leaving you with a leak.
There are three ways to deal with this:
- Don't allocate memory (in this situation you would simply use a vector, but obviously sometimes there's no way around using dynamic allocations)
- Make sure your constructor can never throw after any memory allocations or if it does throw to clean up the memory before throwing. This is going to make some pretty nasty code though in all but the most trivial of constructors
- Use smart pointers