zoukankan      html  css  js  c++  java
  • 栈解旋(unwinding)

    异常被抛出后,从进入try块起,到异常被抛掷前,这期间在栈上的构造的所有对象,都会被自动析构。析构的顺序与构造的顺序相反。这一过程称为栈的解旋(unwinding)。

    例如:

     1 #include<iostream>
     2 using namespace std;
     3 
     4 class A
     5 {
     6 public:
     7     A(int a=0,int b=0)
     8     {
     9         this->a=a;
    10         this->b=b;
    11         cout<<"调用类A的构造函数"<<endl;
    12     }
    13 
    14     ~A(){cout<<"调用类A的析构函数"<<endl;}
    15 
    16 protected:
    17     int a;
    18     int b;
    19 };
    20 
    21 
    22 void myfun()
    23 {
    24     try
    25     {
    26       A a1(1,2),a2(3,4);
    27       cout<<"myfun()要发生异常"<<endl;
    28       throw 1;
    29     }
    30 
    31     catch(int x)
    32     {
    33         cout<<"出现的异常已被处理"<<endl;
    34     }
    35     
    36 
    37     catch(...)//处理不知道什么原因的异常
    38     {
    39         cout<<"程序出现未知的异常"<<endl;
    40     }
    41 }
    42 
    43 
    44 int main()
    45 {
    46     myfun();
    47 
    48     return 0;
    49 }

    上面的代码执行结果为:

    调用类A的构造函数

    调用类A的构造函数

    myfun()要发生异常

    调用类A的析构函数

    调用类A的析构函数

    出现的异常已被处理

    上面的执行结果验证了我们的结论:异常被抛出后,从进入try块起,到异常被抛掷前,这期间在栈上的构造的所有对象,都会被自动析构。

  • 相关阅读:
    8.1.3 CSS3选择器 —— 伪类
    8.1.2 CSS3选择器 —— 结构性伪类
    VI打开和编辑多个文件的命令
    vi全局替换方法
    更改Ubuntu 12.04默认的shel
    如何区分直连串口线和交叉串口线?
    [转]OpenWrt的dl下载地址
    关闭 ubuntu System program problem detected
    linuxC学习
    aa
  • 原文地址:https://www.cnblogs.com/jswu-ustc/p/8546477.html
Copyright © 2011-2022 走看看