Should I be worried about Wmissing-field-initializers and aggregate initialization in C++17?
Asked Answered
G

1

8

I compiled some code with GCC with -Wall and -Wextra enabled. This code produces a warning:

struct A { A(int) {} };
struct B {};

struct C : A, B {};

int main() {
    (void) C{1};
}
main.cpp: In function 'int main()':
main.cpp:11:15: warning: missing initializer for member 'C::<anonymous>' [-Wmissing-field-initializers]
     (void) C{1};
               ^

Should I be worried about that? Is this a bug in GCC for outputting this warning? It seems I have no field to initialize, and no missing parameters.

Gwyngwyneth answered 10/12, 2017 at 5:51 Comment(0)
S
8

C++17 allows you to perform aggregate initialization on classes with base classes. Each base class is effectively considered a member (they come before the direct members of the class). So to aggregate initialization, C has two "members": C::A and C::B.

You only initialized one.

Oh sure, B doesn't actually have anything to initialize. But to -Wall, it's no different from this:

struct C
{
  A a;
  B b;
};

(void) C{1};

This would give a warning too. You would silence it in either case by providing an explicit initializer for B: (void)C{1, {}};.

But as far as the standard is concerned, this is perfectly valid code. B will be value initialized. In either case.

Staggers answered 10/12, 2017 at 6:13 Comment(2)
Oh well... I'm dealing with generic code there, so I would be hard to add the empty parameters :(Gwyngwyneth
@GuillaumeRacicot Would it possibly help you to know the expected number of initializers? These can be counted using SFINAE.Gastrotrich

© 2022 - 2024 — McMap. All rights reserved.