struct A {
int x;
A(A *a) { if (a) a->x = 42;}
};
struct B {
A a1;
A a2;
};
void f()
{
B b{.a1{nullptr}, .a2{&b.a1} };
}
This code is valid.Now if I change the struct definition to
struct B {
A a2;
A a1;
};
it will become UB. Luckily it won't compile because of the difference between the order of declaration and the order of designated initializers.The alternative way is to always initialize the sub-objects in the order of designated initializers (what do we do if not all initializers are provided?), but this would mean that the order of constructor calls wouldn't match the (reversed) order of destructor calls. Or we would need to select the destructor dynamically based on the way the object was initialized.
Upd:
There is an interesting sentence in [class.cdtor] but I don't think it applies here because B has no constructors:
"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."[1]