本文主要是介绍std::exit功能介绍和析构函数调用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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 calledvoid 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 calledTest* new_variablep = new Test("new"); // Destructor of this object will *not* be calledstatic Test static_variable("static"); // Destructor of this object *will* be calledconst int result1 = std::atexit(atexit_handler1); // Handler1 will be calledconst int result2 = std::atexit(atexit_handler2); // Handler1 will be calledif (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
可以看到,只有静态存储对象的析构函数以及注册的函数在程序终止时才会被执行。
这篇关于std::exit功能介绍和析构函数调用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!