'missing initializer for member' for std::string_view member

198 views Asked by At

I thought I understood how struct initialization worked. But apparently not. Here's an innocuous looking struct:

struct Foo {
  int a = 0;
  std::string_view b;
};

Foo bar() {
  return {.a = 47};  // error: missing initializer for member 'Foo::b'
}

I mean, why? Even stranger is that the following fixes the 'error':

struct Foo {
  int a = 0;
  std::string_view b = "";  // Huh?
};

I thought that std::string_view has default initialization so need to explicitly assign it the empty string. I'm obviously missing something here, but not clear what ...

UPDATE:

Like all good shops, we compile with -Wall -Werror -Wextra. All warnings are errors ... as they should be!

1

There are 1 answers

1
Sarah Essam On

This is not about the std::string_view, you would get the same warning for the following piece of code:

struct Foo {
    int a;
    std::string_view b;
};

Foo bar() {
    return {.b = ""};  // error: missing initializer for member 'Foo::a'
}

This is the compiler's way of telling you that you might have forgotten to explicitly initialize the other struct fields. This warning is enabled with -Wextra, If you'd like to keep this option and disable only the missing initializer warning, you can use -Wno-missing-field-initializers.