开发者

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


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.


just a sample to show you when stuff happens

struct B {
    B() {
        print("struct B / constructor B", 1);
    }
};
struct A
{
    B& b;
    A(B& b) : b(b) {
        print("struct A / constructor with B", 1);
    };

};
struct C
{
    B b;
    A a;
    C() : b(),a(b) {
        print("struct C / constructor C", 1);
    };
    void dummy()
    {
        print("dummy",1);
    }
};
struct D
{
    A a;
    B b;
    D() : a(b),b() {

        print("struct D / constructor D", 1);
    };
    void dummy()
    {
        print("dummy",1);
    }
};

int main(int argc, char* argv[])
{
    D dTest;
    dTest.dummy();

    C cTest;
    cTest.dummy();

}

--- output

struct A / constructor with B
struct B / constructor B
struct D / constructor D
dummy
struct B / constructor B
struct A / constructor with B
struct C / constructor C
dummy
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜