class someclass {}; class base { int a; int *pint; someclass objsomeclass; someclass* psomeclass; public: base() { objsomeclass = someclass(); psomeclass = new someclass(); pint = new int(); throw 'constructor failed'; a = 43; } } int main() { base temp(); }
In the above code, the constructor throws. Which objects will be leaked, and how can the memory leaks be avoided?
int main() { base *temp = new base(); }
How about in the above code? How can the memory leaks be avoided after the constructor throws?
Yes it will leak memory. When the constructor throws, no destructor will be called (in this case you don’t show a destructor that frees the dynamically allocated objects, but lets assume you had one).
This is a major reason to use smart pointers – since the smart poitners are full fledged objects, they will get destructors called during the exception’s stack unwind and have the opportunity to free the memory.
If you use something like Boost’s scoped_ptr<> template, your class could look more like:
And you would have no memory leaks (and the default dtor would also clean up the dynamic memory allocations).
To sum up (and hopefully this also answers the question about the
statement):
When an exception is thrown inside a constructor there are several things that you should take note of in terms of properly handling resource allocations that may have occured in the aborted construction of the object:
This means that if your object owns resources, you have 2 methods available to clean up those resources that might have already been acquired when the constructor throws: