Reputation: 3255
Let's consider this code:
#include <vector>
#include <array>
int main()
{
std::vector<std::array<int, 3>> arr;
arr.push_back({ 1,2,3}); // WARNING
arr.push_back({{4,5,6}}); // All good
std::array<int, 3> a1 {1,1,1}; // WARNING
std::array<int, 3> a2 {{2,2,2}}; // All good
std::vector<int> a3 {3,3,3}; // All good
std::vector<int> a4 {{4,4,4}}; // All good
return 0;
}
Everything compiles correctly, and all the vector & arrays contain elements as expected.
However, when using flag -Wmissing-braces
in gcc (tested with 10.2) we get:
<source>:8:27: warning: missing braces around initializer for 'std::__array_traits<int, 3>::_Type' {aka 'int [3]'} [-Wmissing-braces]
8 | arr.push_back({ 1,2,3}); // WARNING
11 | std::array<int, 3> a1 {1,1,1}; // WARNING
Why is gcc showing this warning? Is this a bug as per https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53119 or https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80454 as suggested in How to repair warning: missing braces around initializer?, or is there genuinely something wrong with the 2 marked lines above?
Upvotes: 2
Views: 2143
Reputation: 39818
Those bug reports are about unhelpfully issuing the warning for the special case {0}
, which is valid for initializing any struct
type in C and thus sometimes must be used because such a type is left unspecified.
This code is correct as given; the warning is just the usual result of std::array<T,N>
having to contain a member of type T[N]
, so that additional braces are required if you want to explicitly initialize every level (and sometimes if other brace initialization is in use). If you ask your compiler to be pedantic about such things with -Wmissing-braces
, it does what you asked and warns about the shorthand. (std::vector<int>
doesn’t need extra braces because it’s using an initializer-list constructor, not aggregate initialization.)
Upvotes: 1