且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在施工过程中采用未初始化的班级成员参考合法吗?

更新时间:2023-10-12 08:39:40

应该没问题,但是您由于尚未初始化,因此不允许在 X(Y& y)内使用 y

It should be fine, but you are not allowed to use y inside of X(Y& y) as it was not yet initialized.

表示不是UB的相关部分是:

The relevant part that says it is not UB is:

3.7.5 / 6 n4140(强调是我的)

3.7.5/6 n4140 (emphasis is mine)


类似地,在对象的生存期开始之前但在对象要占用的
存储空间之后,或对象的
生命周期已经结束,并且在
对象所占的存储区被重用或释放之前, 任何引用
原始对象的glvalue都可以使用,但是

Similarly, before the lifetime of an object has started but after the storage which the object will occupy has been allocated or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any glvalue that refers to the original object may be used but only in limited ways.

y 是lvalue(也是glvalue),因此以上内容与此相关。使用此类引用访问变量是UB。

y is lvalue (which is also a glvalue), so above is relevant here. Accessing variables using such reference is UB.

标准还说,引用必须有效(8.3.2 / 5):

Standard also says that reference to be valid it must (8.3.2/5):


...引用应初始化为引用有效的对象或函数。

... A reference shall be initialized to refer to a valid object or function.

但是我没有在标准中找到什么是有效对象。特别是是否意味着其构造函数已被调用。使用指针而不是引用似乎没有这个问题。

But I have not found in standard what is valid object. Especially whether it means that its constructor has already been called. Using pointer instead of reference seems to not have this problem.