Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::array<T> initialization

A std::array<T> is essentially a C-style array wrapped in a struct. The initialization of structs requires braces, and the initialization of arrays requires braces as well. So I need two pairs of braces:

std::array<int, 5> a = {{1, 2, 3, 4, 5}};

But most of the example code I have seen only uses one pair of braces:

std::array<int, 5> b = {1, 2, 3, 4, 5};

How come this is allowed, and does it have any benefits or drawbacks compared to the first approch?

like image 669
fredoverflow Avatar asked Jan 14 '12 15:01

fredoverflow


People also ask

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 initialize STD array std STD?

Initialization of std::array Like arrays, we initialize an std::array by simply assigning it values at the time of declaration. For example, we will initialize an integer type std::array named 'n' of length 5 as shown below; std::array<int, 5> n = {1, 2, 3, 4, 5};

How do you initialize an array in 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.

Is std :: array 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).


1 Answers

The benefit is that you have ... less to type. But the drawback is that you are only allowed to leave off braces when the declaration has that form. If you leave off the =, or if the array is a member and you initialize it with member{{1, 2, 3, 4, 5}}, you cannot only pass one pair of braces.

This is because there were worries of possible overload ambiguities when braces are passed to functions, as in f({{1, 2, 3, 4, 5}}). But it caused some discussion and an issue report has been generated.

Essentially, the = { ... } initialization always has been able to omit braces, as in

int a[][2] = { 1, 2, 3, 4 };

That's not new. What is new is that you can omit the =, but then you must specify all braces

int a[][2]{ {1, 2}, {3, 4} };
like image 188
Johannes Schaub - litb Avatar answered Oct 17 '22 18:10

Johannes Schaub - litb