std::atexit
来自cppreference.com
<tbody>
</tbody>
<tbody class="t-dcl-rev t-dcl-rev-num ">
</tbody><tbody>
</tbody>
| 在标头 <cstdlib> 定义
|
||
| (1) | ||
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; |
(C++11 起) | |
extern "C" using /* c-atexit-handler */ = void(); extern "C++" using /* atexit-handler */ = void(); |
(2) | (仅用于阐述*) |
注册 func 指向的函数,使得在正常程序中止(通过 std::exit() 或从 main 函数返回)时调用它。
|
这些函数将在静态对象析构期间以逆序调用:如果 A 先于 B 被注册,那么对 B 的调用先于对 A 的调用。同样的规则适用于静态对象构造函数和对 |
(C++11 前) |
|
函数可能与拥有静态存储期的对象的析构函数,或彼此间并发调用,这维持了在 A 的注册按顺序早于 B 的注册时,对 B 的调用按顺序早于对 A 的调用的保证,同样的规则适用于静态对象构造函数和对 |
(C++11 起) |
同一函数可以进行多次注册。
如果函数通过异常退出,那么调用 std::terminate。
atexit 是线程安全的:从多个线程调用函数不会引入数据竞争。
保证实现支持注册至少 32 个函数。确切的限制由实现定义。
参数
| func | - | 指向正常程序终止时要调用的函数的指针 |
返回值
在注册成功时返回 0,否则返回非零值。
注解
两个重载有所不同,因为形参 func 的类型不同(语言链接是类型的一部分)。
示例
运行此代码
#include <cstdlib>
#include <iostream>
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 or result_2)
{
std::cerr << "注册失败!\n";
return EXIT_FAILURE;
}
std::cout << "从 main 返回...\n";
return EXIT_SUCCESS;
}
输出:
从 main 返回...
At exit #2
At exit #1
参阅
| 导致非正常的程序终止(不进行清理) (函数) | |
| 导致正常的程序终止并进行清理 (函数) | |
(C++11) |
导致快速程序终止,不进行完全的清理 (函数) |
(C++11) |
注册将于调用 quick_exit 时被调用的函数 (函数) |
atexit 的 C 文档
| |