Coming from this question, I am going a step further:
C* c = static_cast<C*>(malloc(sizeof(C)));
As stated in the referenced question, accessing *c (its members) is undefined behaviour before a constructor is called. But, the pointer itself is valid, of course.
Now within the constructor, the members are available already and I should be able to take the address off.
Putting this together, I conclude that the following is legal:
class Y;
class X
{
Y& y;
public:
X(Y& y) : y(y) { } // non-trivial constructor!
};
class Y
{
X& x;
public:
Y(X& x) : x(x) { }
};
class Z
{
X x;
Y y;
public:
Z() : x(y), y(x) { }
};
as long as the constructor of X does not use the uninitialized reference to Y other than storing it somewhere.
Is this correct or have I overseen some important point (and thus producing UB again)? If I missed something, would it make a difference if I used pointers instead of references?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…