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() 有什么区别?
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
