根據,MECPP 的條款11。開頭一段:
在有兩種情況下會調用解構函式。第一種是在正常情況下刪除一個對象,例如對象超出了範圍或被顯式地delete。第二種是異常傳遞的堆棧輾轉開解(stack-unwinding)過程中,由異常處理系統刪除一個對象。
在上述兩種情況下,調用解構函式時異常可能處於啟用狀態也可能沒有處於啟用狀態。遺憾的是沒有辦法在解構函式內部區分出這兩種情況。因此在寫解構函式時你必須保守地假設有異常被啟用。因為如果在一個異常被啟用的同時,解構函式也拋出異常,並導致程式控制權轉移到解構函式外,C++將調用terminate函數。這個函數的作用正如其名字所表示的:它終止你程式的運行,而且是立即終止,甚至連局部對象都沒有被釋放。
幾乎讓人很費解,所以寫了下面這段code以協助理解:
#include <iostream>
#include <exception>
using namespace std;
class class_test {
public:
class_test(void){}
~class_test(void)
{
// throw bad_alloc();
//如果此處扔出異常將會調用terminate()
cout << "~class_test()....." << endl;
cin.get();
}
private:
};
void funtest0(void)
{
class_test obj;
cout << "f0......" << endl;
throw bad_alloc();
cout << "funtest0()......" << endl;
}
void funtest1(void)
{
class_test obj;
cout << "f1....." << endl;
funtest0();
cout << "funtest1()......" << endl;
}
int main()
try
{
class_test obj;
funtest1();
cin.get();
return 0;
}
catch(bad_alloc &e)
{
cout << e.what() << endl;
cin.get();
}