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块起,到异常被抛掷前,这期间在栈上的构造的所有对象,都会被自动析构。

  • 相关阅读:
    matlab练习程序(灰度图直方图均衡化)
    二叉查找树
    hadoop入门介绍
    配置虚拟机Ubuntu网络连接
    hadoop ubuntu (单节点)部署
    Thrift
    linux打包压缩命令汇总
    [转载]ubuntu 启动流程
    linux命令大全
    Linux文件查找命令find,xargs详述
  • 原文地址:https://www.cnblogs.com/jswu-ustc/p/8546477.html
Copyright © 2011-2022 走看看