用成员初始化成员

发布于 2024-08-20 16:11:34 字数 546 浏览 12 评论 0原文

这是我经常遇到的问题。下面的例子说明了这一点:

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 技术交流群。

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

发布评论

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

评论(1

多情出卖 2024-08-27 16:11:34

由于初始化的顺序未定义

,相反,它是明确定义的。初始化的顺序等于在类中声明成员变量的顺序(并且无论初始化列表的实际顺序如何!因此,最好让初始化列表顺序与声明的顺序匹配)避免令人讨厌的意外)。

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).

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