(C++11 前)
int atexit( /*c-atexit-handler*/* func );
int atexit( /*atexit-handler*/* func );
(C++11 起)
int atexit( /*c-atexit-handler*/* func ) noexcept;
int atexit( /*atexit-handler*/* func ) noexcept;
若执行成功,返回0,否则返回非0.
当程序正常终止(调用exit()或者由main函数返回)时,调用atexit()参数中指定的函数。若程序通过异常退出,则调用std::terminate()
#include <iostream>
#include <cstdlib>
void atexit_handler_1()
{
std::cout << "at exit #1\n";
}
void atexit_handler_2()
{
std::cout << "at exit #2\n";
}
int main()
{
const int result_1 = std::atexit(atexit_handler_1);
const int result_2 = std::atexit(atexit_handler_2);
if ((result_1 != 0) || (result_2 != 0)) {
std::cerr << "Registration failed\n";
return EXIT_FAILURE;
}
std::cout << "returning from main\n";
return EXIT_SUCCESS;
}
结果:
returning from main
at exit #2
at exit #1
注意:atexit
是线程安全的:从数个线程调用函数不引入数据竞争。
保证实现支持注册至少 32
个函数。准确限制是实现定义的。
其他相关函数:
导致非正常的程序终止(不进行清理) (函数) | |
导致正常的程序终止并进行清理 (函数) | |
(C++11) | 导致快速程序终止,不进行完全的清理 (函数) |
(C++11) | 注册将于调用 quick_exit 时被调用的函数 (函数) |