There are two issues one which is a matter of style and the warning.
Although it may not be obvious, aggregate initialization is happening on a temporary which is then being used as an argument to the copy constructor. The more idiomatic to do this initialization would be as follows:
std::array<int, 10> arr = {};
Although this still leaves the warning.
The warning is covered by gcc bug report: - -Wmissing-field-initializers relaxation request and one of the comments says:
[...]Surely, the C++ syntax of saying MyType x = {}; should be supported,
as seen here:
http://en.cppreference.com/w/cpp/language/aggregate_initialization
where for instance:
struct S {
int a;
float b;
std::string str;
};
S s = {}; // identical to S s = {0, 0.0, std::string};
That shouldn't warn for the reasons stated in earlier comments.
and a follow-up comment says:
My statement about zero-initialization was inaccurate (thanks), but
the general point still stands: in C you have to write ' = {0}' since
empty-braces initializer is not supported by the language (you get a
warning with -pedantic); in C++, you can write ' = {}' or 'T foo =
T();', but you don't need to write ' = {0}' specifically.
The latest versions of gcc does not produce this warning for this case, see it live working with gcc 5.1.
We can see this topic also covered in the Clang Developers lists in the thead: -Wmissing-field-initializers.
For reference the draft C++11 standard section 8.5.1
[dcl.init.aggr] says:
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 from an empty initializer list (8.5.4). [
Example:
struct S { int a; const char* b; int c; };
S ss = { 1, "asdf" };
initializes ss.a with 1, ss.b with "asdf", and ss.c with the value of
an expression of the form int(), that is, 0. —end example ]
So as this is valid C++, although as noted using {}
is not valid C99. One could argue that it is only a warning, but this seems like idiomatic C++ using {}
for aggregate initialization and is problematic if we are using -Werror
to turn warnings into errors.
-Werror
which I do. It is good to see the warning was removed it recent versions but that does not help those who can't upgrade :-( – Marquesan({})
is weird and should be discouraged, children will point and laugh at you in the street if you do that). – Samuelson-Wno-xxxx
is useful but in this case I may not want to use-Wno-missing-field-initializers
since I may want the other cases it warns about. Agreed that({})
is indeed weird but if the example was changed tostd::array<int, 10> arr = {};
the question would still stand. – Marquesan({})
is weird would not really be an answer. Probably be considered a bad answer since it now blocks a reasonable edit to the question which would simplify it and remove what is not really the core issue. – Marquesan