我想在类中初始化一堆成员以保持源文件更清晰.但是,对象采用我只通过构造函数接收的参数,并且可以通过赋值在构造函数初始化列表或构造函数中初始化. (第二种选择肯定不会起作用
在标题中
class Foo { public: Foo(Pointer * ptr); private: Pointer * ptr; Member m1{ptr, "SomeText"}; Member m2{ptr, "SomeOtherText"}; }
在CPP
Foo::Foo(Pointer*ptr) : ptr(ptr) { // ... }
现在的问题是:标准是否说明了ptr和m1 / m2之间的初始化顺序?显然,只有在m1和m2之前初始化ptris时,此代码才有效.
这一点得到了标准的保证,即非静态数据成员将按照类定义中的声明顺序进行初始化.它们如何初始化(通过默认成员初始化程序或成员初始化程序列表)以及这些初始化程序的顺序无关紧要.[class.base.init]#13.3
(13.3) – Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).
[ Note: The declaration order is mandated to ensure that base and member subobjects are destroyed in the reverse order of initialization. — end note ]
这意味着,初始化顺序将始终为ptr – > m1 – >平方米.