Search code examples
c++c++14value-initializationlist-initializationaggregate-initialization

How to value-initialize aggregate types with list-initialization


How can one value-initialize aggregate types in C++14 with the list-intialization syntax?

Aggregate_t {}; 

This is seen as aggregate initialization, which produces errors or warnings for uninitialized members of Aggregate_t.

Is this possible at all?

EDIT: examples

struct Aggregate_t {
  int x;
};

int main (int, char**)
{
  Aggregate_t {};
  return 0;
}

Compiling with g++-4.9.2:

main.c++: In function ‘int main(int, char**)’:
main.c++:7:16: warning: missing initializer for member ‘Aggregate_t::x’ [-Wmissing-field-initializers]
   Aggregate_t {};
            ^

Solution

  • [dcl.init.aggr]:

    7 - If there are fewer initializer-clauses in the list than there are members in the aggregate, then each member not explicitly initialized shall be initialized [C++14: from its brace-or-equal-initializer or, if there is no brace-or-equal-initializer,] from an empty initializer list (8.5.4).

    So g++ is being overzealous with its warning; I don't know of a way to avoid it while preserving it in cases where the warning is valid, except of course to use copy-initialization with expected copy elision:

    Aggregate_t a = Aggregate_t();