为什么要按它们声明的顺序初始化成员变量? [英] Why should I initialize member variables in the order they're declared in?

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

问题描述

我今天正在写一些代码,并得到了一个奇怪的编译错误,这似乎是由成员变量以不同的顺序初始化造成的。

I was writing some code today and got a weird compile error, which seems to be caused by initializing member variables in a different order than they were declared.

示例:

class Test {
    int a;
    int b;

public:
    Test() : b(1), a(2) {
    }
};

int main() {
    Test test;
    return 0;
}

然后,如果我使用 -Werror -Wall

$ g++ -Werror -Wall test.cpp
test.cpp: In constructor ‘Test::Test()’:
test.cpp:3:9: error: ‘Test::b’ will be initialized after [-Werror=reorder]
test.cpp:2:9: error:   ‘int Test::a’ [-Werror=reorder]
test.cpp:6:5: error:   when initialized here [-Werror=reorder]
cc1plus: all warnings being treated as errors

我意识到 -Wall 明确要求GCC过度警告,但我认为有一个理由。因此,初始化成员变量的顺序如何?

I realize that -Wall is explicitly asking GCC to go over-the-top with warnings, but I assume there's a reason for all of them. So, how could the order of initializing member variables matter?

推荐答案

原因是因为它们按照它们的顺序初始化,在您的类中声明,而不是在构造函数中初始化它们的顺序,并且它警告您不会使用构造函数的顺序。

The reason is because they're initialized in the order they're declared in your class, not the order you initialize them in the constructor and it's warning you that your constructor's order won't be used.

这是为了帮助防止错误其中 b 的初始化取决于 a ,反之亦然。

This is to help prevent errors where the initialization of b depends on a or vice-versa.

这个排序的原因是因为只有一个析构函数,它必须选择一个逆序来销毁类成员。在这种情况下,最简单的解决方案是使用类中的声明顺序,以确保属性总是以正确的逆序排列。

The reason for this ordering is because there is only one destructor, and it has to pick a "reverse order" to destroy the class member. In this case, the simplest solution was to use the order of declaration within the class to make sure that attributes were always destroyed in the correct reverse order.

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

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