取消对象创建的简洁方法

发布于 2024-12-07 08:03:25 字数 268 浏览 0 评论 0原文

我想知道如何停止/取消由 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 function myObj->Init(). And destroy object if this fails?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

追风人 2024-12-14 08:03:25

以上都不是。

如果由于条件不满足而无法构造对象,则构造函数应使用 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.

人事已非 2024-12-14 08:03:25

新建之前检查?

如果您的先决条件可以在对象自己的内部范围之外进行验证,并且它们在语义上属于调用范围,那么当然......这太棒了!

在构造函数中检查,返回 null 或特殊的东西,不知道如何处理...

在构造函数内检查,并抛出异常。像处理任何其他异常一样处理它。 最佳方法。

new成功且对象处于活动状态后进行检查。调用成员函数myObj->Init()。如果失败则销毁对象?

以这种方式放弃 RAII 是一种倒退

Check before new?

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 constructor, returning null or something special, don't know how to handle ...

Check within the constructor, and throw an exception. Handle it like you handle any other exception. Best approach.

Check after new was successful and object is alive. Call a member function myObj->Init(). And destroy object if this fails?

Abandoning RAII in this manner is a backwards step.

只怪假的太真实 2024-12-14 08:03:25

为对象的构造函数抛出异常。请注意,该对象的析构函数将不会被调用,这与操作符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.

夜清冷一曲。 2024-12-14 08:03:25

也许最好创建总是成功的轻量级构造函数,以及初始化函数,该函数会进行繁重的工作并在错误时抛出异常。

编辑。经过一些批评反馈后,我发现为什么我的建议不符合 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文