什么是出口()和中止()之间的区别? [英] What is the difference between exit() and abort()?
问题描述
在C和C ++,是之间的差异的exit()
和中止()
?我想一个错误(没有一个例外)后结束我的程序。
中止()
退出程序,而无需使用的 的atexit()
第一,没有先调用对象的析构函数。 退出()
同时做两件事之前退出程序。它不叫虽然自动对象的析构函数。因此,
A一;
无效测试(){
静态A B;
A C;
出口(0);
}
将自毁 A
和 B
正常,但不会叫的析构函数ç
。 中止()
不会把没有对象的析构函数。由于这是不幸的,C ++标准描述了确保正确终止的一种替代机制:
使用自动存储时间的对象都摧毁了其功能的程序
的main()
不包含自动对象和执行调用退出()
。控制可以通过抛出一个是陷入异常主要直接传送到这样的
。的main()
()
块引用>结构exit_exception {
INT℃;
exit_exception(INT C):C(C){}
};诠释主(){
尝试{
//把所有code在这里
}赶上(exit_exception急症){
出口(e.c);
}
}而不是调用的
退出()
,安排了code掷exit_exception(exit_ code);
代替。In C and C++, what is the difference between
exit()
andabort()
? I am trying to end my program after an error (not an exception).解决方案
abort()
exits your program without calling functions registered usingatexit()
first, and without calling objects' destructors first.exit()
does both before exiting your program. It does not call destructors for automatic objects though. SoA a; void test() { static A b; A c; exit(0); }
Will destruct
a
andb
properly, but will not call destructors ofc
.abort()
wouldn't call destructors of neither objects. As this is unfortunate, the C++ Standard describes an alternative mechanism which ensures properly termination: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); } }
Instead of calling
exit()
, arrange that codethrow exit_exception(exit_code);
instead.这篇关于什么是出口()和中止()之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!