什么是出口()和中止()之间的区别? [英] What is the difference between exit() and abort()?

查看:114
本文介绍了什么是出口()和中止()之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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() and abort()? I am trying to end my program after an error (not an exception).

解决方案

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);
}

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:

Objects with automatic storage duration are all destroyed in a program whose function main() contains no automatic objects and executes the call to exit(). Control can be transferred directly to such a main() by throwing an exception that is caught in main().

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 code throw exit_exception(exit_code); instead.

这篇关于什么是出口()和中止()之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆