BZ易风

导航

 

概念

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

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

class myException
{
public:
    myException()
    {
        cout << "myException构造" << endl;
    }
    void printError()
    {
        cout << "自定义异常" << endl;
    }
    ~myException()
    {
        cout << "自定义异常析构" << endl;
    }
};
class Person
{
public:
    Person()
    {
        cout << "Person构造" << endl;
    }
    ~Person()
    {
        cout << "Person析构" << endl;
    }
};
int myDevide(int a, int b)
{
    if (b == 0)
    {
        //栈解旋
        //从try 开始 到throw抛出异常之前 所有栈上的对象 都会被释放 这个过程称为栈解旋

        Person p1;
        Person p2;

        //栈解旋2 throw之前
        throw myException(); //匿名对象
    }
    return a / b;
}
void test01()
{
    int a = 10;
    int b = 0;
    try
    {
        myDevide(a, b);
        //栈解旋1 try之后
    }
    catch (myException e)
    {
        e.printError();
    }
}
int main()
{
    test01();
    system("Pause");
    return 0;
}

结果:

两次析构:

myException类会用拷贝构造出另一个对象给catch (myException e), 所以有两个对象,最后会有两次析构

posted on 2021-08-25 10:21  BZ易风  阅读(275)  评论(0编辑  收藏  举报