Let's say I have the following code:
struct mytype { ~mytype() { /* do something like call Mix_CloseAudio etc */ } }; int main() { mytype instant; init_stuff(); start(); return 0; }
Is that destructor guaranteed to be called even if exit() is used from somewhere inside start() ?
No, most destructors are not run on exit() . 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.
Throwing an exception out of a destructor is dangerous. If another exception is already propagating the application will terminate. This basically boils down to: Anything dangerous (i.e. that could throw an exception) should be done via public methods (not necessarily directly).
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 .
It is automatically called when an object is destroyed, either because its scope of existence has finished (for example, if it was defined as a local object within a function and the function ends) or because it is an object dynamically assigned and it is released using the operator delete.
If you call exit
, the destructor will not be called.
From the C++ standard (§3.6.1/4):
Calling the function
void exit(int);
declared in
<cstdlib>
(18.3) terminates the program without leaving the current block and hence without destroying any objects with automatic storage duration (12.4). If exit is called to end a program during the destruction of an object with static storage duration, the program has undefined behavior.
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