Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using std::array with initialization lists

Unless I am mistaken, it should be possible to create a std:array in these ways:

std::array<std::string, 2> strings = { "a", "b" }; std::array<std::string, 2> strings({ "a", "b" }); 

And yet, using GCC 4.6.1 I am unable to get any of these to work. The compiler simply says:

expected primary-expression before ',' token 

and yet initialization lists work just fine with std::vector. So which is it? Am I mistaken to think std::array should accept initialization lists, or has the GNU Standard C++ Library team goofed?

like image 687
Chris_F Avatar asked Nov 19 '11 05:11

Chris_F


People also ask

Is 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.

Are std :: arrays zero initialized?

std::array::array For elements of a class type this means that their default constructor is called. For elements of fundamental types, they are left uninitialized (unless the array object has static storage, in which case they are zero-initialized).

What is the use of initialization list in C++?

Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.


1 Answers

std::array is funny. It is defined basically like this:

template<typename T, int size> struct std::array {   T a[size]; }; 

It is a struct which contains an array. It does not have a constructor that takes an initializer list. But std::array is an aggregate by the rules of C++11, and therefore it can be created by aggregate initialization. To aggregate initialize the array inside the struct, you need a second set of curly braces:

std::array<std::string, 2> strings = {{ "a", "b" }}; 

Note that the standard does suggest that the extra braces can be elided in this case. So it likely is a GCC bug.

like image 65
Nicol Bolas Avatar answered Oct 06 '22 23:10

Nicol Bolas