关于析构函数在stack-unwinding中扔出异常的代码分析

王朝system·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

根据,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();

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航