我已經閱讀了幾篇文章,以及可以從構造函數中拋出異常的地方。但是,我注意到,如果從構造函數中拋出異常,它不會調用基類或其數據成員的析構函數。考慮下面的例子:從構造函數中拋出異常在C++中
#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的析構函數像關閉文件/套接字和刪除堆分配一樣執行一些清理操作,這可能會導致問題。
所以我的問題是爲什麼和什麼時候可以從構造函數中拋出異常。
請注意,如果您在'main'中捕獲到異常,則會調用析構函數。見[這裏](http://ideone.com/nQemT)。 – 2012-03-10 01:54:59
在您習慣使用異常之前,您可能需要閱讀[this](http://stackoverflow.com/questions/1744070/why-should-exceptions-be-used-conservatively)及其相關問題。 – Shahbaz 2012-03-10 02:15:27