Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11: Correct std::array initialization?

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?

like image 480
Byzantian Avatar asked Jan 06 '13 01:01

Byzantian


People also ask

Which is correct way to initialize array in C C++?

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.

Does std :: array initialize?

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.

How do you declare and initialize an array in C++?

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.


1 Answers

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

like image 140
Pubby Avatar answered Sep 30 '22 20:09

Pubby