问题描述
在 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() 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!