命名空间
变体
操作

std::atexit

来自 cppreference.cn
< cpp‎ | utility‎ | program
 
 
 
 
定义于头文件 <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 的调用之前。这同样适用于静态对象构造函数与 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

[编辑] 另请参阅

导致程序异常终止(不进行清理)
(函数) [编辑]
导致程序正常终止并进行清理
(函数) [编辑]
导致程序快速终止而不完全清理
(函数) [编辑]
注册一个函数,在调用 std::quick_exit 时被调用
(函数) [编辑]
C 文档 关于 atexit