struct A {
B one;
C two;
};
struct B {
B() {
cout << "init B" << endl;
}
}
struct C {
C() {
cout << "init C" << endl;
}
}
Mixing up the order is confusing: A{.two=B(),.one=A()}
since `two` is initialized after `one` despite coming before (the comma operator <expr a>, <expr b> usually means `expr a` happens before `expr b`.This case is a little contrived, but run the evolution forward: you can have members that depend on each other, or have complex initialization logic of their own. There, debugging the specific order of events is important.
{ val x$1 = B() val x$2 = A() A(.one = x$2, .two = x$1) }
This maintains left-to-right evaluation order while allowing you to pass arguments in any order.
There is probably some dark and forbidden reason why C++ can't do that.
ETA: That's basically what the post does.
struct A { A(A*); };
A* f(struct B *b);
struct B {
A a1;
A a2;
B(): a1(f(this)), a2(f(this)) {}
};
//in a different translation unit
A* f(B *b)
{
return &b->a1; //or a2, we don't know
}
[0] https://godbolt.org/z/xMb64ssYKFurthermore your code possibly contains undefined behavior depending on the behavior of the constructor of A.
>your code possibly contains undefined behavior
Only if f() returns a pointer to a2 (which is my point). Or did you imply that in the case when f() returns a pointer to a1 and it gets passed to the constructor of a1, provenance matters?
"During the construction of an object, if the value of the object or any of its subobjects is accessed through a glvalue that is not obtained, directly or indirectly, from the constructor's this pointer, the value of the object or subobject thus obtained is unspecified." [0]
Reading an unspecified value isn't UB, that's good, but I don't understand why the standard says 'unspecified' because it clearly can be indeterminate if a sub-object hasn't been initialized yet.