为什么要按照声明的顺序初始化成员变量?
我今天写了一些代码,得到一个奇怪的编译错误,这似乎是由于初始化成员变量的顺序与声明的顺序不同.
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.
相关文章