为什么要按照声明的顺序初始化成员变量?

Why should I initialize member variables in the order they#39;re declared in?(为什么要按照声明的顺序初始化成员变量?)
本文介绍了为什么要按照声明的顺序初始化成员变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天写了一些代码,得到一个奇怪的编译错误,这似乎是由于初始化成员变量的顺序与声明的顺序不同.

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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)