以前、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()