Is it possible to prevent omission of aggregate initialization members?

I have a struct with many members of the same type, like this

struct VariablePointers {
   VariablePtr active;
   VariablePtr wasactive;
   VariablePtr filename;
};

The problem is that if I forget to initialize one of the struct members (e.g. wasactive), like this:

VariablePointers{activePtr, filename}

The compiler will not complain about it, but I will have one object that is partially initialized. How can I prevent this kind of error? I could add a constructor, but it would duplicate the list of variable twice, so I have to type all of this thrice!

Please also add C++11 answers, if there's a solution for C++11 (currently I'm restricted to that version). More recent language standards are welcome too, though!


Solution 1:

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.

Solution 2:

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