Can I ignore the gcc warning: ‘Foo::m_bar’ should be initialized in the member initialization list [-Weffc++]

前端 未结 2 628
清酒与你
清酒与你 2021-01-01 12:34
struct Bar
{
    Bar() {}
};


struct Foo
{
    Foo() = default;
    Bar m_bar;
};

int main()
{
    Foo foo;
}

When using C++11 default

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-01 12:58

    You can ignore or suppress the warning. This is a misinterpretation of one of the Effective C++ guidelines. The guideline says to prefer initialisation to assignment, but in your example, m_bar will be initialised. Your code is correct.

    Source: Jonathan Wakely in GCC's bug tracker:

    # Item 12: Prefer initialization to assignment in constructors.

    Replaced by Item 4: "Make sure that objects are initialized before they're used", and G++ misinterprets the original item anyway and warns about any member without a mem-initializer, which is very annoying: there's no point initializing a std::string, it has a perfectly safe default constructor. My -Wmeminit patch for PR 2972 should replace the current warning for this item, as it only warns about members left uninitialized by the constructor.

    (And as it's a known issue, there's no need to report it as a bug again.)

提交回复
热议问题