gpt4 book ai didi

c++ - 类内初始化顺序与构造函数初始化列表

转载 作者:太空狗 更新时间:2023-10-29 20:20:18 24 4
gpt4 key购买 nike

我想在类中初始化一堆成员以保持源文件更干净。但是,这些对象采用我仅通过构造函数接收的参数,并且可以在构造函数初始化列表中或通过赋值在构造函数中进行初始化。 (第二个选项肯定行不通。)基本上是这样的:

在标题中

class Foo
{

public:
Foo(Pointer * ptr);

private:

Pointer * ptr;
Member m1{ptr, "SomeText"};
Member m2{ptr, "SomeOtherText"};
}

在 CPP 中

Foo::Foo(Pointer*ptr) : 
ptr(ptr)
{
// ...
}

现在的问题是:标准是否说明了 ptrm1/m2 之间的初始化顺序?显然,只有当 ptrm1m2 之前初始化时,这段代码才有效。

最佳答案

这是由标准保证的,非静态数据成员将按照它们在类定义中的声明顺序进行初始化。它们的初始化方式(通过默认成员初始化器或成员初始化器列表)以及这些初始化器的顺序无关紧要。

[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 -> m2

关于c++ - 类内初始化顺序与构造函数初始化列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52220762/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com