取消对象创建的简洁方法
我想知道如何停止/取消由 new()
引发的对象的创建。也许如果某些先决条件失败并且不需要该对象。
- 在
new
之前检查? - 在构造函数内进行检查,返回
null
或其他特殊内容,不知道如何处理... - 在
new
成功且对象处于活动状态后进行检查。调用成员函数myObj->Init()
。如果失败的话会销毁对象吗?
I'm wondering how to stop/cancel the creation of an object, risen by new()
. Maybe if some preconditions fail and the object isn't needed.
- Check before
new
? - Check within constructor, returning
null
or something special, don't know how to handle ... - Check after
new
was successful and object is alive. Call a member functionmyObj->Init()
. And destroy object if this fails?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
以上都不是。
如果由于条件不满足而无法构造对象,则构造函数应使用
throw
语句抛出异常。None of the above.
If the object cannot be constructed because of unmet conditions, the constructor should throw an exception with the
throw
statement.如果您的先决条件可以在对象自己的内部范围之外进行验证,并且它们在语义上属于调用范围,那么当然......这太棒了!
在构造函数内检查,并抛出异常。像处理任何其他异常一样处理它。 最佳方法。
以这种方式放弃 RAII 是一种倒退。
If your preconditions can be verified outside of the object's own inner scope and if they semantically belong in the calling scope, then sure... this is great!
Check within the constructor, and throw an exception. Handle it like you handle any other exception. Best approach.
Abandoning RAII in this manner is a backwards step.
为对象的构造函数抛出异常。请注意,该对象的析构函数将不会被调用,这与
操作符delete
不同,它将被自动调用以回收分配的内存。Throw an exception for the object's constructor. Note that the object's destructor will not be called, unlike
operator delete
, which will be called automatically to reclaim the allocated memory.也许最好创建总是成功的轻量级构造函数,以及初始化函数,该函数会进行繁重的工作并在错误时抛出异常。
编辑。经过一些批评反馈后,我发现为什么我的建议不符合 RAII 要求:
“资源是在初始化期间获取的,在它们可用之前没有机会使用它们”。
我不会更改我原来的帖子,将其作为典型的设计错误示例可能会有所帮助。
Maybe it's better to make lightweight constructor which always succeeds, and Initialize function that makes heavy work and throws exception on error.
Edit. After some critical feedback, I found why my suggestion doesn't meet RAII requirements:
"Resources are acquired during initialization, when there is no chance of them being used before they are available".
I don't change my original post, it may be helpful to have this as typical design error sample.