用成员初始化成员 [英] Initializing members with members
问题描述
这是我经常遇到的问题。下面的例子说明了它:
This is a problem I come across often. The following examples illustrates it:
struct A {
int m_SomeNumber;
};
struct B {
B( A & RequiredObject );
private:
A & m_RequiredObject;
};
struct C {
C( );
private:
A m_ObjectA;
B m_ObjectB;
};
执行 C
的构造函数像这样:
The implementation of the constructor of C
looks something like this:
C::C( )
: B( m_ObjectA )
{ }
由于未定义初始化顺序, m_ObjectA
可能在调用 m_ObjectB
的构造函数时未初始化,导致未定义的行为。强制某种顺序的初始化的一种方法是使成员指针和初始化它们在构造函数体中,从而强制正确的顺序,但这是丑陋的几个原因。有什么办法强制某个初始化命令使用构造函数的初始化列表?
Since the order of initialization is not defined, m_ObjectA
might be uninitialized when the constructor of m_ObjectB
is called, resulting in undefined behavior. One way to force a certain order of initialization would be to make the members pointers and initialize them in the constructor body, thus forcing the correct order, but this is ugly for several reasons. Is there any way to force a certain initializtion order using the initialization-list of the constructor? If not, do you have any other suggestions how to handle this.
推荐答案
未定义初始化
Since the order of initialization is not defined
相反,它是定义明确的。初始化的顺序等于在你的类中声明成员变量的顺序(并且这与初始化列表的实际顺序无关!因此,让初始化列表顺序与声明的顺序匹配是一个好主意避免令人讨厌的惊喜)。
On the contrary, it is well-defined. The order of initialization is equal to the order in which the member variables are declared in your class (and that’s regardless of the actual order of the initialization list! It’s therefore a good idea to let the initialization list order match the order of the declarations to avoid nasty surprises).
这篇关于用成员初始化成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!