Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor initialization order and reference passing

Hi I have a question about the constructor initialization order. Given below

struct B {}
struct A
{
    B& b;
    A(B& b) : b(b) {}
}
struct C
{
    B b;
    A a;
    C() : b(),a(b) {}
}
struct D
{
    A a;
    B b;
    D() : a(b),b() {}
}

I know that C is valid as b gets initialized before a. But what about D? b wouldn't have been constructed yet, but the address should already be known, so it should be safe?

Thanks

like image 294
Cookie Avatar asked Oct 16 '25 13:10

Cookie


1 Answers

They're both valid because A doesn't call into B at all. If A accessed a data member or member function of B, then that would be invalid. In the existing case of A, it's impossible to produce an invalid example.

like image 160
Puppy Avatar answered Oct 19 '25 15:10

Puppy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!