What is the difference between exit() and abort()?(exit() 和 abort() 有什么区别?)
问题描述
在 C 和 C++ 中,exit() 和 abort() 有什么区别?我试图在出现错误后结束我的程序(不是异常).
In C and C++, what is the difference between exit() and abort()? I am trying to end my program after an error (not an exception).
推荐答案
abort() 退出程序而不调用使用 注册的函数atexit() 首先,而不是先调用对象的析构函数.exit() 在退出您的程序之前执行这两项操作.但是它不会为自动对象调用析构函数.所以
abort() exits your program without calling functions registered using atexit() first, and without calling objects' destructors first. exit() does both before exiting your program. It does not call destructors for automatic objects though. So
A a;
void test() {
static A b;
A c;
exit(0);
}
会正确地析构a和b,但不会调用c的析构函数.abort() 不会调用两个对象的析构函数.由于这是不幸的,C++ 标准描述了一种确保正确终止的替代机制:
Will destruct a and b properly, but will not call destructors of c. abort() wouldn't call destructors of neither objects. As this is unfortunate, the C++ Standard describes an alternative mechanism which ensures properly termination:
具有自动存储期的对象都在一个程序中销毁,该程序的函数main()不包含自动对象并执行对exit()的调用.通过抛出在 main() 中捕获的异常,可以将控制直接转移到这样的 main().
Objects with automatic storage duration are all destroyed in a program whose function
main()contains no automatic objects and executes the call toexit(). Control can be transferred directly to such amain()by throwing an exception that is caught inmain().
struct exit_exception {
int c;
exit_exception(int c):c(c) { }
};
int main() {
try {
// put all code in here
} catch(exit_exception& e) {
exit(e.c);
}
}
不要调用exit(),而是安排代码throw exit_exception(exit_code);.
Instead of calling exit(), arrange that code throw exit_exception(exit_code); instead.
这篇关于exit() 和 abort() 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:exit() 和 abort() 有什么区别?
基础教程推荐
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- c++ STL设置差异 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
