为什么初始化列表顺序必须匹配成员声明顺序?

2021-12-30 00:00:00 constructor c++ initializer-list

如果初始化器列表顺序与类中的变量顺序不匹配,为什么 gcc 会抛出嘶嘶声?

Why does gcc throw a hissy fit if the initializer list order doesn't match variable order in the class?

class myClass
{
public:
   int A;
   int B;
   myClass();
};

myClass::myClass() :
B(1),
A(2)
{}

将导致:

file.h:274: warning: 'myClass::A' will be initialized after
file.h:273: warning:   'int myClass::B
file.cpp:581: warning:   when initialized here

发出这种警告有什么具体原因吗?按照与类中定义的顺序不同的顺序初始化类的变量是否存在任何风险?

Is there any specific reason why this kind of warning is issued? Are there any risks associated with initializing variables of a class in order different than they are defined within the class?

(注意,有一个问题触及主题,但答案是几乎因为它应该如此"而没有给出任何关于为什么它应该被订购的理由,或者这不正常有什么问题 - 我想知道为什么存在这样的限制- 有人可以举个例子说明它可能适得其反吗?)

(note, there is a question which touches the subject, but the answers are pretty much "because it should be so" without giving any rationale as to why it should be ordered, or what's wrong with this being out of order - I'd like to know why such a restriction exists - could someone give an example where it may backfire maybe?)

推荐答案

该警告试图防止您可能依赖数据成员的错误顺序的情况.假设你认为 B 在 A 之前被初始化,然后你做这样的事情:

The warning is trying to prevent situations where you might be relying on the wrong ordering of the data members. Say you think B is initialized before A, and then you do something like this:

myClass::myClass() :
B(42), A(B) {}

在这里,您有未定义的行为,因为您正在读取未初始化的 B.

Here, you have undefined behaviour because you are reading from an uninitialized B.

相关文章