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?
I believe that the top answer is wrong and would still leak memory. The destructor for the class members will not be called if the constructor throws an exception (because it never completed its initialization, and perhaps some members have never reached their constructor calls). Their destructors are only called during the class's destructor call. That only makes sense.
This simple program demonstrates it.
With the following output (using g++ 4.5.2):
If your constructor fails partway then it is your responsibility to deal with it. Worse, the exception may be thrown from your base class' constructor! The way to deal with these cases is by employing a "function try block" (but even then you must carefully code the destruction of your partially initialized object).
The correct approach to your problem would then be something like this:
If you run it you will get the expected output where only the allocated objects are destroyed and freed.
You can still work it out with smart shared pointers if you want to, with additional copying. Writing a constructor similar to this:
Good luck, Tzvi.