在初始化的声明中,我可以使用未初始化数据的引用吗? [英] In a declaration with initialization, can I use a reference to uninitialized data?

查看:210
本文介绍了在初始化的声明中,我可以使用未初始化数据的引用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数来创建和返回一个对象。它也有一个副作用,写一个成功标志到一个布尔变量:

I have a function that creates and returns an object. It also has a side-effect, writing a success flag into a boolean variable:

struct MyObject
{
    ...
    int field1;
    char field2;
    bool field3;
};

MyObject CreateMyObject(bool& success)
{
    ...
}

通过纯巧合,它发生,我必须存储成功标志在我的对象。所以我可以用这个明显的方式写:

By pure coincidence it happens that I have to store the success flag in my object. So I can write it in this obvious way:

bool success;
MyObject x = CreateMyObject(success);
x.field3 = success;

或以这种方式:

MyObject x = CreateMyObject(x.field3);

第二种方式涉及未定义的行为,从多个赋值到 field3 或其他?

Does the second way involve undefined behavior, from multiple assignments to field3 or otherwise?

(我的 struct 不是POD, p>

(My struct is not a POD, if that matters)

推荐答案

编写标准的人已经想到了这种情况,坏消息是它被禁止:

The people who wrote the standard have thought of this case, and the bad news is that it is forbidden:


12.7构造和销毁



1 - 对于具有非平凡构造函数的对象,在构造函数开始执行之前对象的任何非静态成员或基类都会导致未定义的行为。 [...]

12.7 Construction and destruction

1 - For an object with a non-trivial constructor, referring to any non-static member or base class of the object before the constructor begins execution results in undefined behavior. [...]

有一个很接近你的代码的例子:

There is an example given that is pretty close to your code:

struct W { int j; };
struct X : public virtual W { };
struct Y {
  int *p;
  X x;
  Y() : p(&x.j) { // undefined, x is not yet constructed
  }
};

在这种情况下,未定义的行为正在形成一个指向未完成会员;形成对成员的引用是类似的。

In that case, the undefined behaviour is forming a pointer to a member of a not-yet-constructed member; forming a reference to a member is similar enough.

我认为很清楚,为了将引用传递给你的构造函数,你必须参考到构造函数开始执行之前的对象成员。

I think it's pretty clear that in order to pass the reference into your constructor, you'd have to take the reference (to the member of the object) before the constructor begins execution.

这篇关于在初始化的声明中,我可以使用未初始化数据的引用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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