构造函数中的异常 [英] Exceptions in constructors

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

问题描述

在C ++中,对象的生命周期在构造函数成功完成时开始。在构造函数中,对象还不存在。

In C++, the lifetime of an object begins when the constructor finishes successfully. Inside the constructor, the object does not exist yet.


问:从构造函数中释放异常意味着什么?

Q: What does emitting an exception from a constructor mean?

A:这意味着构造失败,对象永远不存在,其生存期从未开始。 [ source ]

A: It means that construction has failed, the object never existed, its lifetime never began. [source]

我的问题是:这同样适用于Java吗?例如,如果我把 this 移动到另一个对象,然后我的构造函数失败,会发生什么?

My question is: Does the same hold true for Java? What happens, for example, if I hand this to another object, and then my constructor fails?

Foo()
{
    Bar.remember(this);
    throw new IllegalStateException();
}

这是否定义良好? Bar 现在有对非对象的引用吗?

Is this well-defined? Does Bar now have a reference to a non-object?

推荐答案

这可能发生在这个施工过程中泄漏当你抛出一个异常)。

This can happen whenever this leaks during construction (not just when you throw an exception).

这是一个非常有问题的情况,因为一些通常假设的保证在这种情况下不成立(例如最终字段在构建期间可能会改变它们的值。)

It's a very problematic situation, because some commonly assumed guarantees don't hold true in this situation (for example final fields could seem to change their value during construction).

因此,您绝对应避免泄露 this 在构造函数中。

Therefore you should definitely avoid leaking this in the constructor.

这篇IBM developerWorks文章描述了构建对象时需要注意的事项以及这些预防措施背后的原因。虽然文章根据多线程讨论主题,但在未知/不可信代码在构建期间引用 this 时,您可能在单线程环境中具有类似的问题。

This IBM developerWorks article describes the precautions to take when constructing objects and the reasoning behind those precautions. While the article discusses the subject in the light of multi-threading, you can have similar problems in a single-threaded environment when unknown/untrusted code gets a reference to this during construction.

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

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