如何在C ++中构造函数中处理失败? [英] How to handle failure in constructor in C++?

查看:123
本文介绍了如何在C ++中构造函数中处理失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在类构造函数中打开一个文件。可能的是,开口可能失效,然后物体构造不能完成。如何处理这个失败?抛出异常?如果这是可能的,如何在非throw构造函数中处理它?<​​/ p>

I want to open a file in a class constructor. It is possible that the opening could fail, then the object construction could not be completed. How to handle this failure? Throw exception out? If this is possible, how to handle it in a non-throw constructor?

推荐答案

如果对象构造失败, 。

If an object construction fails, throw an exception.

替代方案是可怕的。如果构造成功,您必须创建一个标志,并在每种方法中检查。

The alternative is awful. You would have to create a flag if the construction succeeded, and check it in every method.

这篇关于如何在C ++中构造函数中处理失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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