栈解旋(unwinding)

时间:2021-08-25
本文章向大家介绍栈解旋(unwinding),主要包括栈解旋(unwinding)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

概念

异常被抛出后,从进入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;
}

结果:

原文地址:https://www.cnblogs.com/yifengs/p/15183801.html