我想使用初始化列表来初始化对象以简化对象管理,但问题是对象之间会相互引用。
//B::B(A &a) //The only available constructor for B
class AB
{
A m_a;
B m_b;
AB()
: m_a()
, m_b(m_a)
...
};
这是标准允许的吗?据我了解,应该是这样的,假设类中的成员声明是 A,然后是 B,初始化列表中的顺序无关紧要,因为它们将按类中的物理顺序进行初始化。
最佳答案
Is this allowed by standard? From what I understand, it should be, given that member declaration within class are A, then B, order in initialization list doesn't matter, as they will be initialized by their physical order within class.
是的,初始化的顺序就是类中成员属性声明的顺序。此外,根据 B
构造函数的作用,将引用(或指针)传递给尚未初始化的对象是正确的(尽管接近边缘)只要引用(或指针)只要引用或指针被存储,但对象未被使用。
关于c++ - 带有内部引用的初始化列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11199779/