c++ class 成员初始化序列

c++ class member initialization sequence

我知道在 class 中,成员按照列出的顺序进行初始化。这是否适用于将变量分组为 publicprivate 等?我的困惑是,我无法弄清楚是否存在偏好,例如 private 成员按照它们在 public 成员之前列出的顺序进行初始化,而不管私有变量相对于 [=] 列出的位置20=] 在 class 声明中(我知道对基础 class 成员存在这种偏见)

class 初始化的规则在 [class.base.init]/11

中详细说明

In a non-delegating constructor, initialization proceeds in the following order:

  • First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list.

  • Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).

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

8 Finally, the compound-statement of the constructor body is executed.

[ Note: The declaration order is mandated to ensure that base and member subobjects are destroyed in the reverse order of initialization. —end note ]

强调我的

因此,当我们查看项目符号 3 时,它明确指出成员是按照其在定义中出现的顺序构造的。这意味着无论 privatepublic 或它们在 class 成员初始化列表中的列出方式如何,它们都将按照声明的顺序构造。

非静态数据成员按照声明的顺序进行初始化。

通过编译以下代码,您可以测试是否启用了警告:

// Example program
#include <iostream>
#include <string>

class Test {

private:
    int a;

public:
    int b;

    Test() : a(0), b(0) {}

};

class TestPrivatePriority {

public:
    int b;

    TestPrivatePriority() : a(0), b(0) {}

private:
    int a;

};

class TestPublicPriority {

private:
    int a;

public:
    int b;

    TestPublicPriority() : b(0), a(0) {}

};

int main()
{
  Test t;
  TestPrivatePriority t1;
  TestPublicPriority t2;

  return 0;
}

这将产生以下不言自明的警告:

In constructor 'TestPrivatePriority::TestPrivatePriority()':
25:9: warning: 'TestPrivatePriority::a' will be initialized after [-Wreorder]
20:9: warning:   'int TestPrivatePriority::b' [-Wreorder]
22:5: warning:   when initialized here [-Wreorder]
 In constructor 'TestPublicPriority::TestPublicPriority()':
35:9: warning: 'TestPublicPriority::b' will be initialized after [-Wreorder]
32:9: warning:   'int TestPublicPriority::a' [-Wreorder]
37:5: warning:   when initialized here [-Wreorder]