C++ atexit

(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 个函数。准确限制是实现定义的。

其他相关函数:

abort

导致非正常的程序终止(不进行清理)
(函数)

exit

导致正常的程序终止并进行清理
(函数)

quick_exit

(C++11)

导致快速程序终止,不进行完全的清理
(函数)

at_quick_exit

(C++11)

注册将于调用 quick_exit 时被调用的函数
(函数)

参考:std::atexit - C++中文 - API参考文档

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值