c++ - C++构造函数抛出异常

标签 c++ exception-handling constructor

我在这里和其他地方阅读了几篇文章,其中可以从构造函数中抛出异常。但是,我注意到如果构造函数抛出异常,它不会调用基类或其数据成员的析构函数。考虑以下示例:

#include <iostream>
using namespace std;
struct C
{
    C() { cout << __FUNCTION__ << endl;  }
    ~C() { cout << __FUNCTION__ << endl; }
};

struct E: public C
{
    C c;
    E() { cout << __FUNCTION__ << endl; throw 4; }
    ~E() { cout << __FUNCTION__ << endl; }
};

int main()
{
    E e;
}


$ g++ test.cpp; ./a.exe
C
C
E
terminate called after throwing an instance of 'int'
Aborted (core dumped)

在这种情况下,E 的构造函数抛出异常,但作为数据成员或作为基类的 C 的析构函数未被调用。现在,如果 C 的析构函数执行一些清理操作,如关闭文件/套接字和删除堆分配,这可能会导致问题。

所以我的问题是为什么以及何时可以从构造函数中抛出异常。

最佳答案

如果您捕获到错误,析构函数将运行。当在 C++ 中抛出未捕获的异常时,运行时调用 std::terminate .默认情况下,std::terminate 调用 std::abort它特别不会在退出时调用析构函数。

有了这个版本:

#include <iostream>
using namespace std;
struct C
{
    C() { cout << __FUNCTION__ << endl;  }
    ~C() { cout << __FUNCTION__ << endl; }
};

struct E: public C
{
    C c;
    E() { cout << __FUNCTION__ << endl; throw 4; }
    ~E() { cout << __FUNCTION__ << endl; }
};

int main()
{
    try {
        E e;
    } catch(...) {
    }

    return 0;
}

我得到输出:

C
C
E
~C
~C

关于c++ - C++构造函数抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9643220/

相关文章:

c++ - 每次我知道我正在处理无符号值时,我都应该使用 "unsigned"吗?

c# - ASP.NET WEB API 2 : Exception Handler and Logger not handling all errors

java - Java中如何构造二维数组?

c++ - 在另一个类 C++ 的构造函数中实例化一个类的对象?

c++ - 在纯虚类对象的容器中查找

c++ - 模板和函数指针混淆

c++ - 在多线程环境中使用 std::call_once() 进行初始化

ruby-on-rails - Hoptoad v. Exceptional v. exception_notification v. exception_logger

c++ - 纠正 C++ 中的异常

c# - 继承过程中的构造函数调用层次——带参数和不带参数