用成员初始化成员
这是我经常遇到的问题。下面的例子说明了这一点:
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
的构造函数的实现看起来像这样:
C::C( )
: B( m_ObjectA )
{ }
由于初始化的顺序没有定义,当 m_ObjectA
的构造函数< code>m_ObjectB 被调用,导致未定义的行为。强制执行某种初始化顺序的一种方法是创建成员指针并在构造函数主体中初始化它们,从而强制执行正确的顺序,但由于多种原因,这很丑陋。有没有办法使用构造函数的初始化列表强制执行特定的初始化顺序?如果没有,您还有其他建议如何处理这个问题吗?
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;
};
The implementation of the constructor of C
looks something like this:
C::C( )
: B( m_ObjectA )
{ }
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
,相反,它是明确定义的。初始化的顺序等于在类中声明成员变量的顺序(并且无论初始化列表的实际顺序如何!因此,最好让初始化列表顺序与声明的顺序匹配)避免令人讨厌的意外)。
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).