C++11 引入了一种完成程序执行的新方法——std::quick_exit
。
引用 N3242 18.5(第 461 页):
[[noreturn]] void quick_exit(int status) noexcept;
Effects: Functions registered by calls to
at_quick_exit
are called in the reverse order of their registration, except that a function shall be called after any previously registered functions that had already been called at the time it was registered. Objects shall not be destroyed as a result of callingquick_exit
. If control leaves a registered function called byquick_exit
because the function does not provide a handler for a thrown exception,terminate()
shall be called. [ Note:at_quick_exit
may call a registered function from a different thread than the one that registered it, so registered functions should not rely on the identity of objects with thread storage duration. — end note ] After calling registered functions,quick_exit
shall call_Exit(status)
. [ Note: The standard file buffers are not flushed. See: ISO C 7.20.4.4. — end note ]
std::abort(void)
和 std::_Exit(int status)
的定义只在传递状态给父进程的能力上不同,它提出了我的问题。
这是否意味着 std::quick_exit
和 std::abort
在语义上的唯一区别是 std::quick_exit
调用使用 std::at_quick_exit
注册的函数并允许设置返回状态?
引入此功能的基本原理是什么?
最佳答案
有一篇很好的文章 available here ,我简单总结一下。添加此功能是为了专门解决使用线程时干净地结束程序的困难。本质上,退出是由高度异步的事件启动的,用户关闭用户界面,管理员关闭机器等等。这与程序启动的线程的状态无关,它们几乎总是处于高度不可预测的状态。
在理想情况下,程序的 main() 函数要求线程退出,通常通过发出事件信号,等待线程结束,然后退出 main() 以通过 exit() 彻底关闭。然而,这个理想非常很难实现。一个线程可能深埋在系统调用中,例如,等待一些 I/O 完成。或者它正在阻塞需要由另一个线程以正确顺序发出信号的同步对象。结果很少令人愉快,真正的程序经常在退出时陷入僵局。或者当关闭命令意外时崩溃。
对于这个问题有一个简单且非常诱人的解决方法:调用 _exit() 代替。 Kaboom,程序结束,操作系统扫出弹片。但显然根本没有进行任何清理,有时会出现非常困惑的问题,例如半写文件或不完整的 dbase 事务。
std::quick_exit() 提供了替代方案。与 _exit() 类似,但仍然可以选择执行一些代码,无论是在 at_quick_exit 中注册的内容。
关于c++ - std::quick_exit 和 std::abort 有什么区别,为什么需要 std::quick_exit?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9758495/