如果从c ++中的构造函数抛出异常,如何清理初始化的资源 [英] How to clean initialized resources if exception thrown from constructor in c++

查看:173
本文介绍了如果从c ++中的构造函数抛出异常,如何清理初始化的资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前一天我在面试中遇到这个问题。

解决方法如何清除已初始化的资源(如果从c ++的构造函数中抛出异常)?



<方案

诀窍是使用 RAII (资源获取是初始化)来管理资源。



成员然后使用智能指针而不是原始指针,一旦从构造函数抛出异常,它将自动执行清除作业。



良好读取: br>
Herb Sutter的优秀GotW文章建筑失灵


Some day before I faced this question in a interview. So just guide me.

How to clean initialized resources if exception thrown from constructor in c++?

解决方案

The trick is to use RAII(resource acquisition is initialization) to manage resources.

If you have pointer members then use smart pointers instead of raw pointers which will automagically do the cleanup job once a exception is thrown from constructor.

Good Read:
Herb Sutter's excellent GotW article "Construction Failures"

这篇关于如果从c ++中的构造函数抛出异常,如何清理初始化的资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆