在施工过程中采用未初始化的班级成员参考合法吗? [英] Is taking uninitialized references of class members during construction legal?

查看:88
本文介绍了在施工过程中采用未初始化的班级成员参考合法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


来自这个问题,我要走的更远:

C* c = static_cast<C*>(malloc(sizeof(C)));

如所引用的问题所述,在构造函数之前,访问* c(其成员)是未定义的行为叫。但是,指针本身当然是有效的。

As stated in the referenced question, accessing *c (its members) is undefined behaviour before a constructor is called. But, the pointer itself is valid, of course.

现在在构造函数中,成员已经可用,我应该可以删除地址。

Now within the constructor, the members are available already and I should be able to take the address off.

总之,我得出以下结论是合法的:

Putting this together, I conclude that the following is legal:

class Y;
class X
{
    Y& y;
public:
    X(Y& y) : y(y) { } // non-trivial constructor!
};
class Y
{
    X& x;
public:
    Y(X& x) : x(x) { }
};
class Z
{
    X x;
    Y y;
public:
    Z() : x(y), y(x) { } 
};

只要X的构造函数除了将其存储在某个地方外,不使用对Y的未初始化引用。

as long as the constructor of X does not use the uninitialized reference to Y other than storing it somewhere.

这是正确的还是我监督了一些重要的观点(因此又产生了UB)?如果我错过了一些东西,如果我使用指针而不是引用会有所不同吗?

Is this correct or have I overseen some important point (and thus producing UB again)? If I missed something, would it make a difference if I used pointers instead of references?

推荐答案

应该没问题,但是您由于尚未初始化,因此不允许在 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.

这篇关于在施工过程中采用未初始化的班级成员参考合法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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