考虑下面的类
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/