【C++异常机制】栈解旋

关于异常机制请看这篇文章,附链接:

C++异常机制详解icon-default.png?t=M276https://blog.csdn.net/qq_43471489/article/details/123495003栈解旋是指,在抛出异常的时候,在try语句块内部,抛异常前所有在栈上构造的对象都将会被析构。下面通过程序举例说明:

#include <iostream>
using namespace std;

class TestClass
{
public:
	TestClass()
	{
		cout << "构造函数" << endl;
	}
	~TestClass()
	{
		cout << "析构函数" << endl;
	}
};

void CreateObject()
{
	TestClass t1, t2;
	cout << "创建对象" << endl;

	throw TestClass();
}

int main()
{
	try
	{
		CreateObject();
	}
	catch (TestClass t)
	{
		cout << "TestClass 类型异常" << endl;
	}
	catch (...)
	{
		cout << "其他异常" << endl;
	}

	system("pause");
	return 0;
}

运行结果可以看到,抛异常后调用了两次析构函数

posted @ 2022-03-16 11:37  Mindtechnist  阅读(18)  评论(0编辑  收藏  举报  来源