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

前端 未结 3 609
有刺的猬
有刺的猬 2020-11-30 11:22

Let\'s say I have the following code:

struct mytype
{
    ~mytype() { /* do something like call Mix_CloseAudio etc */ }
};

int main()
{
    mytype instant;
         


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 11:43

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

    Calling the function void exit(int); declared in (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++.

提交回复
热议问题