构造函数初始化顺序和引用传递
您好,我有一个关于构造函数初始化顺序的问题。下面给出
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它们都是有效的,因为 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.
只是一个向您展示事情发生时的示例
--- 输出
just a sample to show you when stuff happens
--- output