std::exit函数调用后,系统会终止当前执行的程序(无论主线程还是子线程调用,该程序都会被终止),在终止之前会有一些清理步骤会被执行:
静态存储对象(静态的或者全局的)会被析构(按照构造的逆顺序),而std::atexit注册的函数也会被调用,局部对象(栈区)和新建对象(堆区)不会被调用析构函数。
直接看测试用例:
#include <string>
#include <iostream>
struct Test
{
std::string m_str;
Test(const std::string& str) {
m_str = str;
}
~Test() {
std::cout << "destructor " << m_str << std::endl;
}
};
Test global_variable("global"); // Destructor of this object *will* be called
void atexit_handler1()
{
std::cout << "atexit handler1\n";
}
void atexit_handler2()
{
std::cout << "atexit handler2\n";
}
int main()
{
Test local_variable("local"); // Destructor of this object will *not* be called
Test* new_variablep = new Test("new"); // Destructor of this object will *not* be called
static Test static_variable("static"); // Destructor of this object *will* be called
const int result1 = std::atexit(atexit_handler1); // Handler1 will be called
const int result2 = std::atexit(atexit_handler2); // Handler1 will be called
if (result1 != 0 || result2 != 0)
{
std::cerr << "atexit registration failed\n";
return EXIT_FAILURE;
}
std::cout << "test\n";
std::exit(EXIT_SUCCESS);
std::cout << "this line will *not* be executed\n";
}
执行结果如下:
test
atexit handler2
atexit handler1
destructor static
destructor global
可以看到,只有静态存储对象的析构函数以及注册的函数在程序终止时才会被执行。