In a declaration with initialization, can I use a reference to uninitialized data?

痞子三分冷 提交于 2019-12-23 12:49:11

问题


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;

Or in this way:

MyObject x = CreateMyObject(x.field3);

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

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


回答1:


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

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.



来源:https://stackoverflow.com/questions/22202672/in-a-declaration-with-initialization-can-i-use-a-reference-to-uninitialized-dat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!