Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will exit() or an exception prevent an end-of-scope destructor from being called?

Tags:

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() ?

like image 348
Truncheon Avatar asked Apr 19 '10 14:04

Truncheon


People also ask

Does exit call destructor?

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.

What happens if exception is thrown from destructor?

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).

Are destructors automatically called whenever an object goes out of scope?

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 .

What happens when destructor is not called?

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.


1 Answers

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.

like image 110
James McNellis Avatar answered Oct 10 '22 17:10

James McNellis