stack unwinding

本文探讨了C++中异常处理机制下析构函数的行为,包括如何在异常发生时调用析构函数进行资源清理,并展示了静态和外部对象的行为差异。通过示例代码解释了异常处理流程及终止处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当抛出异常,程序的控制权由try block交给catch block时,C++ runtime自动调用try block里的所有auto和register对象的dtor函数,这个过程叫stack unwinding。

1> static和extern对象不调用dtor。
2> dtor的调用顺序和ctor的调用顺序相反。
3> 在构造对象时如果抛出了异常,对于其内部的子对象、或者数组,只有正确执行了ctor的才会调用dtor来析构。
4> 在析构对象时如果抛出了异常,且该异常未被处理,程序将调用terminate中止。

#include <iostream> using namespace std; struct E // 自定义的异常类型 { const char* message; E(const char* arg) : message(arg) { } }; void my_terminate() // 自定义的terminate函数 { cout << "Call to my_terminate" << endl; }; struct A { A() { cout << "In constructor of A" << endl; } ~A() { cout << "In destructor of A" << endl; throw E("Exception thrown in ~A()"); // 在下面的异常活跃时,dtor中又发生了异常。这是第二次异常,将导致程序中止 } }; struct B { B() { cout << "In constructor of B" << endl; } ~B() { cout << "In destructor of B" << endl; } }; int _tmain(int argc, _TCHAR* argv[]) { set_terminate(my_terminate); try { cout << "In try block" << endl; A a; B b; throw ("Exception thrown in try block of main()"); // 此处发生了第一次异常 } catch (const char* e) { cout << "Exception: " << e << endl; } catch (...) { cout << "Some exception caught in main()" << endl; } cout << "Resume execution of main()" << endl; return 0; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值