Possible Duplicate:
Will exit() or an exception prevent an end-of-scope destructor from being called?
In C++, when the application calls exit(3) are the destructors on the stack supposed to be run to unwind the stack?
A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete .
While returning from a function, destructor is the last method to be executed. The destructor for the object “ob” is called after the value of i is copied to the return value of the function. So, before destructor could change the value of i to 10, the current value of i gets copied & hence the output is i = 3.
In C++, we can manage resources by objects, i.e. acquiring resource in Ctor, and releasing it in Dtor (RAII). This relies on C++'s automatic destructor invocation.
Yes, a destructor (a.k.a. dtor) is called when an object goes out of scope if it is on the stack or when you call delete on a pointer to an object.
No, most destructors are not run on exit()
.
C++98 §18.3/8 discusses this.
Essentially, when exit
is called static objects are destroyed, atexit
handlers are executed, open C streams are flushed and closed, and files created by tmpfile
are removed. Local automatic objects are not destroyed. I.e., no stack unwinding.
Calling abort
lets even less happen: no cleanup whatsoever.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With