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

标签 c++ memory constructor initialization-list

考虑下面的类

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

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

最佳答案

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?

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

关于c++ - 构造函数初始化列表中使用的变量顺序重要吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34761697/

相关文章:

将函数应用于连续元素的 C++ 算法

c++ - 成对和元组计算嵌套类型

c++ - 如何报告自己的内存使用情况 C++

c++ - 在范围内创建指针时,当指针超出范围时,指向的变量会发生什么?

c++ - 调用父类(super class)构造函数的规则是什么?

C++获取其他用户的appdata路径

c++ - 在 Linux 上使用控制台编译 C++ 时出现问题

c++ - 为什么我们需要在 C++ 中显式声明指针类型?

c# - c#构造函数的问题

Java:何时创建*任何*类的监听器?