throw后局部变量的析构。

当C++函数中抛出异常后,退出该函数时,所有局部变量会正常析构。文章通过实例展示了在函数f()抛出异常后,局部对象在异常处理过程中被正确析构的过程,并探讨了程序在throw后的行为,包括停止运行及错误信息提示。
 
// test.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <cstdlib>
#include <new>
#include <iostream>  
#include <string>  

using namespace std;  


class object
{
public:
	~object()
	{
		cout<<"~object()"<<endl;
	}
	object()
	{
		cout<<"object()"<<endl;
	}
protected:
private:
};

int f()
{
	object obj;
	cout<<"f()"<<endl;
	throw 0xffff;
	cout<<"throwed"<<endl;
	return 1;
}

int main() { 
	try
	{
		f();
		cout<<"end f()"<<endl;
	}
	catch (int x)
	{
		cout<<x<<endl;
	}
	getchar();
}   


程序输出:

object()
f()
~object()
65535

 

main函数改成如下之后:

 

int main() { 

	f();
	cout<<"end f()"<<endl;

	getchar();
} 


提示有未处理的异常,“继续”之后的输出为:

object()
f()
throwed
~object()
end f()

 

也就是说在函数f() throw异常之后跳出f()时,局部变量进行了析构。

 

实际运行后一个main生成的exe。将会在throw之后停止运行。并显示:

This application has requested the Runtime to terminate it in an unusual way.

Please contact the application's support team for more information.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值