C++程序退出机制

C++程序退出机制

从几个std函数入手分析:

  • std::exit,用于正常流程退出,由用户显式调用。(main()函数返回 = 调用main内部局部变量的dtor + std::exit(0))。
  • std::terminate,用于异常流程退出,一般由库函数调用。
  • std::abort,直接终止程序。

其中只有std::exit()函数会执行清理动作,比如调用析构函数和执行std::atexit注册过的函数。

另外,std::asssert()断言失败时会输出错误信息 + 调用std::abort()。

具体描述可以看cppreference。

一图胜千言:
版权所有侵权必究

所谓static存储期对象,就是全局对象或者作用域内static声明的对象或者类的static成员。

接收到信号如何终止?

整个程序直接终止,除非信号被捕获。

多线程程序的终止?

参考上面的描述,我们只需要关注多线程程序中单个线程内调用std::exit()或std::abort()时会发生什么 ——

事实上,在一个线程中调用std::exit()或者std::abort()都会引起整个程序的终止。

需要注意,多线程环境中调用std::exit()时只会调用static存储期对象或者调用线程的thread_local对象的析构函数,而不会调用其他线程的thread_local对象的析构函数,符合cppreference描述:

The destructors of objects with thread local storage duration that are associated with the current thread, the destructors of objects with static storage duration, and the functions registered with std::atexit are executed concurrently, while maintaining the following guarantees:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值