12

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?

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
  • I'm not sure it _is_ allowed by the standard -- possibly the compilers that accept that code are based on an earlier C++11 draft, or simply give a warning since it's an extension allowing ill-formed code. – ildjarn Jan 14 '12 at 15:55
  • @ildjarn According to Johannes, it is allowed. – fredoverflow Jan 14 '12 at 16:10

1 Answers1

14

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} };
Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212