构造函数初始化列表中使用的变量顺序重要吗?

Is the order of variable used in constructor initialization list important?

考虑以下 class

class A 
{
int a;
double b;
float c;
A():a(1),c(2),b(3)
{}
}

我们是否必须按照我们在 class 中声明的相同顺序在初始化列表中使用变量?初始化列表中变量的顺序是否会影响 class/variables 的内存分配? (考虑这种情况,如果 class 有很多 bool 变量,很多 double 变量等等。)

Variables will initialiaze in the order of declaration in the class.

初始化列表中变量的顺序不影响。

在我们的示例中,初始化变量的顺序将是:a, b, c

And Will the order of variables in initialization list has any impact on memory allocation of that class/variables?

无效。

Do we have to use variables in initialization list in the same order as we declared in class?

初始化列表的顺序对初始化顺序没有影响。因此它避免了在初始化列表中使用真实顺序的误导行为。

存在依赖关系时出现问题:

class A 
{
  int a;
  double b;
  float c;
  // initialization is done in that order: a, b, c
  A():a(1), c(2), b(c + 1) // UB, b is in fact initialized before c
  {}
};

Will the order of variables in initialization list has any impact on memory allocation of that class/variables?

初始化列表的顺序对布局或初始化顺序没有影响。

首先,

Do we have to use variables in initialization list in the same order as we declared in class?

否,但您最好这样做以避免混淆。因为 member initializers 在列表中的顺序无关紧要。

The order of member initializers in the list is irrelevant: the actual order of initialization is as follows:

1) If the constructor is for the most-derived class, virtual base classes are initialized in the order in which they appear in depth-first left-to-right traversal of the base class declarations (left-to-right refers to the appearance in base-specifier lists)

2) Then, direct base classes are initialized in left-to-right order as they appear in this class's base-specifier list

3) Then, non-static data members are initialized in order of declaration in the class definition.

4) Finally, the body of the constructor is executed

其次,

And Will the order of variables in initialization list has any impact on memory allocation of that class/variables?

不,因为根本不重要。