构造函数初始化顺序和引用传递

发布于 2024-12-05 16:55:15 字数 312 浏览 0 评论 0原文

您好,我有一个关于构造函数初始化顺序的问题。下面给出

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() {}
}

我知道 C 是有效的,因为 b 在 a 之前初始化。但是D呢? b 还没有被构造,但是地址应该已经知道,所以它应该是安全的?

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

过去的过去 2024-12-12 16:55:15

它们都是有效的,因为 A 根本不调用 B。如果 A 访问了 B 的数据成员或成员函数,那么这将是无效的。在 A 的现有情况下,不可能产生无效示例。

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.

标点 2024-12-12 16:55:15

只是一个向您展示事情发生时的示例

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();

}

--- 输出

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文