为什么必须初始化列表顺序匹配成员声明顺序? [英] Why must initializer list order match member declaration order?

查看:447
本文介绍了为什么必须初始化列表顺序匹配成员声明顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于为什么必须初始化列表顺序匹配成员声明顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆