C++ exit abort與destructor

#include 
#include 

class X
{
  int i;
public:
  X(int i): i(i)
  {
  }
  ~X()
  {
    std::cout << "~X," << i <<  std::endl;
  }
};
static X a(0);
int main()
{
  X a(1);
  //exit(0);
  //abort();
  return 0;
}

從main return時 如預期 先呼叫function scope內的X1的destructor,才再是static X0的destructor。
那如果是exit呢? 只有X0 destructor被呼叫。

為什麼呼叫了exit不是強制直接結束程式而還會呼叫static variable destructor?
參考C++03的 18.3 Start and termination

The function exit() has additional behavior in this International Standard:
First, objects with static storage duration are destroyed and functions registered by calling atexit are
called. Non-local objects with static storage duration are destroyed in the reverse order of the completion
of their constructor. (Automatic objects are not destroyed as a result of calling exit().)
...
The function exit() never returns to its caller.

如果要直接強制離開可呼叫abort

The function abort() has additional behavior in this International Standard:
— The program is terminated without executing destructors for objects of automatic or static storage duration and without calling the functions passed to atexit()

但須注意 abort()會產生core dump
在linux下則可以呼叫_exit(0); 要

#include  

參考: https://stackoverflow.com/questions/7054685/are-destructors-run-when-calling-exit

This entry was posted in C++ Language. Bookmark the permalink.

Leave a Reply