初始化顺序问题 [英] Initialization order issues

查看:139
本文介绍了初始化顺序问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定代码示例:

class B {
    //Some contents.
};

class C {
    private:
        B& b;
};

class A {
    private:
        B b;
        C c;
};

类C具有对b的引用,因此需要使用它进行初始化。 A类包含B的实例和C的实例。

Class C has a reference to a b, so it needs to be initialized with it. Class A contains an instance of B and an instance of C.

我的问题是:我可以用A中的B实例初始化A中的C实例打扰构造函数)?第二,我需要在A中执行B的任何显式初始化,或者它是默认初始化的,因为它是类中的类类型。

My question is: Can I initialize the C instance in A with the B instance in A (assuming I did bother to put the constructors in)? Secondly, do I need to perform any explicit initialization of the B in A, or is it default initialized since its a class type within a class?

推荐答案

成员变量按它们在类声明中声明的顺序进行初始化(,即使您在构造函数的初始化列表中具有不同的顺序),因此是,正在初始化时间 c ,将初始化 b ,您可以使用 b 来初始化 c

Member variables are initialised in the order that they are declared in the class declaration (even if you have them in a different order in the initialisation list of the constructor), so yes, by the time c is being initialised, b will be initialised, and you can use b to initialise c.

如Ricardo Cardenes所说,在类定义中声明 c 之前的 b (这意味着您将传递 C :: C 对未初始化的 B 的引用),但如果您使用 C :: C 。首先声明 b 更安全,因为虽然你不能在 C ::里面使用 b C 现在,您可能会在未来忘记该引用指向未初始化的 B ,并导致UB。

As Ricardo Cardenes notes, it will still work even if you declare c before b in the class definition (which means you will pass C::C a reference to an uninitialised B) however you cause undefined behaviour if you use the object inside C::C. It's safer to declare b first, because although you may not use b inside C::C now, you might in the future and forget that the reference refers to an uninitialised B, and cause UB.

没有,你不必显式初始化 b (除非 POD ),除非你不希望它是默认构造的。所以这段代码是你想要的(再次,如果 B 不是POD):

And no, you do not have to explicitly initialise b (unless it is POD) unless you don't want it to be default-constructed. So this code would be what you want (again, if B isn't POD):

A::A() : c(b) { }

这篇关于初始化顺序问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆