C++显式声明在默认构造函数中触发警告

C++ Explicit declaration triggers a warning in the default constructor

在一个 Code::Blocks v13.12 项目中,我有一个名为 Drawable 的 class,它有一个名为 rotation.

的浮点成员变量

我注意到在 Drawable 的默认构造函数中显式声明 rotation 会触发以下警告:

'Drawable::rotation' should be initialized in the member initialization list [-Weffc++]

但是,在其定义旁边显式声明 rotation 不会这样做。

我想知道的是,为什么会这样:

Drawable() {
    rotation = 0.f;
}

给我一个成员初始化警告,同时:

class Drawable
{
    ...
    float rotation = 0.f;
    ...
}

还有这个:

Drawable() : rotation(0.f) {}

毫无怨言地编译?

-Weffc++ warning的描述如下:

Warn about violations of the following style guidelines from Scott Meyers' Effective C++ series of books:

  • Define a copy constructor and an assignment operator for classes with dynamically-allocated memory.
  • Prefer initialization to assignment in constructors.
  • Have operator= return a reference to *this.
  • Don't try to return a reference when you must return an object.
  • Distinguish between prefix and postfix forms of increment and decrement operators.
  • Never overload &&, ||, or ,.

您看到的警告包含在第 4 项中:确保对象在之前已初始化 他们使用 Effective C++ 3rd edition 表示(释义):

The rules of C++ stipulate that data members of an object are initialized before the body of a constructor is entered.

和:

A better way to write the [...] constructor is to use the member initialization list instead of assignments [...] constructor yields the same end result [...] but it will often be more efficient.

和(强调我的措辞):

The assignment-based version first called default constructors to initialize the member variables then promptly assigned new values on top of the default-constructed ones. All the work performed in those default constructions was therefore wasted. The member initialization list approach avoids that problem,

在 C++11 中 in class member initializers (which also avoids this warning) can simplify initialization if most of your member variables have default values, the one disadvantage is that until C++14 this make your class a non-aggregate