Is it possible to prevent omission of aggregate initialization members?

For clang and gcc you can compile with -Werror=missing-field-initializers that turns the warning on missing field initializers to an error. godbolt

Edit: For MSVC, there seems to be no warning emitted even at level /Wall, so I don't think it is possible to warn on missing initializers with this compiler. godbolt


Here is a trick which triggers a linker error if a required initializer is missing:

struct init_required_t {
    template <class T>
    operator T() const; // Left undefined
} static const init_required;

Usage:

struct Foo {
    int bar = init_required;
};

int main() {
    Foo f;
}

Outcome:

/tmp/ccxwN7Pn.o: In function `Foo::Foo()':
prog.cc:(.text._ZN3FooC2Ev[_ZN3FooC5Ev]+0x12): undefined reference to `init_required_t::operator int<int>() const'
collect2: error: ld returned 1 exit status

Caveats:

  • Prior to C++14, this prevents Foo from being an aggregate at all.
  • This technically relies on undefined behaviour (ODR violation), but should work on any sane platform.