23

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

Truncheon
  • 916
  • 2
  • 12
  • 25

3 Answers3

29

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.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
18

Yes, calling exit() means the destructor will not be called:

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 an exception is thrown, on the other hand, the destructor will be called. This is the basis of exception safety in C++.

Péter Török
  • 114,404
  • 31
  • 268
  • 329
3

Exceptions will call destructors, so long as something in the program catches the exception. If the exception exits the main() function without being caught, the standard does not require the runtime to unwind the stack to clean up.

Using a

try{
  // code
}catch(...){ //that elipsis should actually appear in your code
             //it doesn't mean I omitted code here.
  //code
}

in your main() function will guarantee that every exception is caught, and all destructors are called.

Ken Bloom
  • 57,498
  • 14
  • 111
  • 168
  • What is the consequence of not unwinding the stack to clean up? If you just want the software to shutdown due to some error and `throw std::runtime_error("Some error text")` and do not catch it. Will every object created before be securely deleted? – Manuel Oliveira Sep 25 '21 at 18:34