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