gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:02:07 25 4
gpt4 key购买 nike

Code::Blocks v13.12 项目中,我有一个名为 Drawable 的类,它有一个名为 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 (这也避免了这个警告)可以简化初始化,如果你的大多数成员变量都有默认值,一个缺点是直到 C++14 这个 make your class a non-aggregate .

关于C++显式声明在默认构造函数中触发警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27791580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com