【发布时间】:2013-01-01 10:48:12
【问题描述】:
我曾经认为在C++中,如果一个构造函数抛出异常,这个“部分构造”的类的析构函数是不会被调用的。
但在 C++11 中似乎不再适用:我用 g++ 编译了以下代码,并将“X destructor”打印到控制台。这是为什么呢?
#include <exception>
#include <iostream>
#include <stdexcept>
using namespace std;
class X
{
public:
X() : X(10)
{
throw runtime_error("Exception thrown in X::X()");
}
X(int a)
{
cout << "X::X(" << a << ")" << endl;
}
~X()
{
cout << "X destructor" << endl;
}
};
int main()
{
try
{
X x;
}
catch(const exception& e)
{
cerr << "*** ERROR: " << e.what() << endl;
}
}
输出
Standard out:
X::X(10)
X destructor
Standard error:
*** ERROR: Exception thrown in X::X()
【问题讨论】:
-
这里有一个liveworkspace link 显示输出