When an exception is thrown, then the block where it is thrown is unwinded from stack:
int main ()
{
try
{
Object x; // doesn't throw
Object y; // throws
cout << "wonderful";
}
catch (...)
{
cout << "fail";
}
}
When Object
allocates on construction memory on heap and deallocates it properly on destruction, then there should be no memory leak, because stack unwinding calls destructor of x
(not of y
, but Object
guarantees, that when constructor failing, then no memory leak). As far all right, isn't it?
Let's go into depth:
int main ()
{
Object x; // doesn't throw
double *d = new double[256*256*256]; // doesn't throw
Object y; // throws
cout << "wonderful";
delete[] d;
}
Because of good education, I want to clean my trash up by myself, and not let do it the OS. I know, that every modern OS deletes by itself heap memory of a program which terminates unexpected (or expected, but no explicit deallocation). So in the upper case, the deallocation of d
would do my OS, but x
would be still properly deallocating its memory (because of stack unwinding and destructor call) before OS would do it, right?
What about that:
#include <cstdlib>
int main ()
{
Object x; // doesn't throw
try { Object y; } // throws
catch (...) { cout << "fail"; exit(EXIT_FAILURE); }
cout << "working and working...";
cin.get();
}
Is the destructor of x
called before exit
gives control back to OS?
And more in depth:
void Object::be_stupid ()
{
Object a; // doesn't throw
try { Object b; }// throws
catch (...) { exit(EXIT_FAILURE); }
}
void main ()
{
Object x; // doesn't throw
try { x.be_stupid(); } // exits program
}
Is the constructor of x
called before exit
gives control back to OS? If yes, then exit
"unwinds" all surrounding stacks including main()
, right?
Ok, got it thanks to polkadotcadaver: never use
exit()
, propagate exceptions untilmain()
and do there a simplereturn
- all stackObjects
will be deallocated by their own destructor before OS takes control.