exit()和abort()有什么区别? [英] What is the difference between exit() and 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()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!