我有這個程序,派生類的ctor拋出異常。該程序只是一個示例程序,我只是想了解異常處理的概念。類的構造函數中異常處理的行爲
class A{
public:
A() {}
~A(){std::cout << "DTOR called - A!!" << std::endl;}
};
class B : public A
{
public:
B():A()
{
try
{
init();
}
catch(...)
{
std::cout << "Inside catch block in B's Ctor!!" << std::endl;
throw this;
}
}
void init() { throw 0; }
~B() {std::cout << "DTOR called - B!!" << std::endl; }
};
int main()
{
try{
B *b = new B;
std::cout << "Äfter B's ctor called in try block!!" << std::endl;
delete b;
std::cout << "Äfter B's dtor called in try block!!" << std::endl;
}
catch(B* b)
{
delete b;
b = NULL;
std::cout << "Exception Occurred in B!!" << std::endl;
}
catch(A* a)
{
delete a;
a = NULL;
std::cout << "Exception Occurred in A!!" << std::endl;
}
catch(...)
{
std::cout << "Exception Occured!!" << std::endl;
}
return EXIT_SUCCESS;
}
預期的輸出是它應該進入B的catch塊,並且應該調用第一個B的dtor,然後調用A的dtor。但上述程序的輸出是:
Inside catch block in B's Ctor!!
DTOR called - A!!
DTOR called - B!!
DTOR called - A!!
Exception Occurred in B!!
我想問這是爲什麼A類的析構函數調用了兩次,當它只是引入了B類的catch塊,並呼籲只有B類的析構函數? 也請告訴我是否在這裏犯了一些錯誤。 任何幫助表示讚賞
編輯:
class B : public A
{
public:
B():A()
{
try
{
szName = new char[100];
init();
}
catch(...)
{
std::cout << "Inside catch block in B's Ctor!!" << std::endl;
throw this;
}
}
void init() { throw 0; }
~B()
{
delete szName;
std::cout << "DTOR called - B!!" << std::endl;
}
char *szName;
};
在這裏,我在構造函數try塊創建了一個字符指針類B.分配的內存被拋出異常之前。現在在這種情況下,如果我沒有發現類B的異常,會不會有內存泄漏?
見http://www.gotw.ca/gotw/066.htm – 2014-10-07 06:33:29