在构造函数中终止对象创建 [英] Terminate object creation in constructor

查看:66
本文介绍了在构造函数中终止对象创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何在C ++中处理构造函数中的失败?

C ++中是否有任何模式,所以如果出现故障,我可以终止在构造函数中的对象创建?那么调用构造函数的客户端会获得有关obj创建失败的信息?

解决方案

是的,您可以:引发异常.这几乎是唯一明智的方法.通过选择适当的异常类(标准或您自己的异常类)并提供良好的错误消息等,您就可以告诉调用者出了什么问题.

常见问题解答有更多详细信息.

Possible Duplicate:
How to handle failure in constructor in C++?

Is there any pattern in C++ so i could terminate object creation in constructor if something fails? And so client that invoke constructor got information about failed obj creation?

解决方案

Yes, you can: throw an exception. This is pretty much the only sensible way. By choosing the appropriate exception class (either standard or your own) and supplying a good error message etc you'll be able to tell the caller what's gone wrong.

The FAQ has more details.

这篇关于在构造函数中终止对象创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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