If I initialize a std::array as follows, the compiler gives me a warning about missing braces
std::array<int, 4> a = {1, 2, 3, 4};
This fixes the problem:
std::array<int, 4> a = {{1, 2, 3, 4}};
This is the warning message:
missing braces around initializer for 'std::array<int, 4u>::value_type [4] {aka int [4]}' [-Wmissing-braces]
Is this just a bug in my version of gcc, or is it done intentionally? If so, why?
Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index.
std::array contains a built-in array, which can be initialized via an initializer list, which is what the inner set is. The outer set is for aggregate initialization.
A typical declaration for an array in C++ is: type name [elements]; where type is a valid type (such as int , float ...), name is a valid identifier and the elements field (which is always enclosed in square brackets [] ), specifies the length of the array in terms of the number of elements.
This is the bare implementation of std::array
:
template<typename T, std::size_t N> struct array { T __array_impl[N]; };
It's an aggregate struct whose only data member is a traditional array, such that the inner {}
is used to initialize the inner array.
Brace elision is allowed in certain cases with aggregate initialization (but usually not recommended) and so only one brace can be used in this case. See here: C++ vector of arrays
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With