Namespaces
Variants

std::atexit

来自 zh.cppreference.net
 
 
 
 
定义于头文件 <cstdlib>
int atexit( /*c-atexit-handler*/* func );
int atexit( /*atexit-handler*/* func );
(1) (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 的调用之前发生。同样的顺序规则也适用于静态对象构造函数与 atexit 的调用之间的关系:见 std::exit。

(C++11 前)

这些函数可能与具有静态存储期对象的销毁以及彼此之间并发调用,但保证如果 A 的注册在 B 的注册之前被顺序确定,则 B 的调用在 A 的调用之前被顺序确定,同样的顺序规则也适用于静态对象构造函数与 atexit 的调用之间的关系:见 std::exit。

(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 || result_2)
    {
        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

参见

导致程序异常终止(不进行清理)
(函数)
导致程序正常终止并进行清理
(函数)
(C++11)
导致程序快速终止但不完全清理
(函数)
注册在调用 std::quick_exit 时要执行的函数
(函数)
C 文档 for atexit