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

  • 相关阅读:
    WPF Video Tutorials
    英语词汇看病
    回车键的含义
    勘误《新概念》IV
    2010年春季C语言程序设计答疑时间地点安排
    勘误《新概念》III
    A potentially dangerous Request.Form value was detected from the client
    推荐WPF的好书(图书)
    *英语词汇交通
    英语词汇房地产
  • 原文地址:https://www.cnblogs.com/jswu-ustc/p/8546477.html
Copyright © 2020-2023  润新知