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() 有什么区别?


基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01