문제

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)

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top