Will (global) static variables be destroyed at program end? [duplicate]

蓝咒 提交于 2019-11-28 11:50:32

The destructors of file or namespace scope objects get called when the control flow leaves main().

If an exception leaves main() then it's implementation defined whether the destructors of any objects get called. With modern compilers the destructors won't be called in this case to allow easy inspection of the program state when the unhandled exception was thrown. Early C++ implementations used exception mechanism based on setjmp/longjmp which would unwind the stack while searching for the exception handler and hence calling destructors even if no suitable exception handler was eventually found.

If an application terminates with _exit() or _Exit() or std::quick_exit() no destructors get called.

The destructors for objects with static lifetime (all of the cases you mention define objects with static lifetime—although I don't think that an object in a constexpr can have a non-trivial destructor) are called from within exit(), in the reverse order the objects were constructed.

Returning from main causes exit to be called with the return value, so returning from main will cause these destructors to be called. Other means of program termination (abort(), assertion failure, _exit(), etc.) will not call destructors.

If the objects are in a DLL (.so under Unix), the destructors will normally be called when the DLL is unloaded.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!