异常被抛出后,从进入try块起,到异常被抛掷前,这期间在栈上的构造的所有对象,都会被自动析构。析构的顺序与构造的顺序相反。这一过程称为栈的解旋(unwinding)。
#pragma warning(disable : 4996)
#include <iostream>
using namespace std;
class Test
{
public:
Test(int a,int b)
{
this->a = a;
this->b = b;
cout << "Test构造函数" << endl;
}
~Test()
{
cout << "Test析构函数" << endl;
}
private:
int a, b;
};
void MyFun()
{
Test t1(1, 2), t2(3, 4);
cout << "定义了两个栈变量,异常抛出后测试栈变量的如何被析构" << endl;
throw 1;
}
int main()
{
try
{
MyFun();
}
catch (int e)
{
cout << "接收到int类型异常" << endl;
}
catch (...)
{
cout << "未知类型异常" << endl;
}
system("pause");
return 0;
}