7

In c++ primer(5th Edition), it is mentioned that std::array assignment from braced list of values is not allowed.

Because the size of the right-hand operand might differ from the size of the left-hand operand, the array type does not support assign and it does not allow assignment from a braced list of values.

Below code is given as an example.

  std::array<int, 10> a1 = {0,1,2,3,4,5,6,7,8,9}; 
  std::array<int, 10> a2 = {0}; // elements all have value 0
  a1 = a2; // replaces elements in a1
  a2 = {0}; // error: cannot assign to an array from a braced list

However, when I compile this code with c++11 compiler it works fine. Is this allowed now or am I missing something?

Christophe
  • 68,716
  • 7
  • 72
  • 138
bornfree
  • 2,308
  • 1
  • 23
  • 33

1 Answers1

4

Yes, a std::array can be assigned from a braced list. It just works normally under C++11 rules - the class doesn't have to do anything special to support it. Consider:

struct S {int x; int y;};
int main() {
  S s{1, 2};
  s = {3, 4};
}

Being an aggregate, S can be constructed from brace-init list. Further, S has an implicitly declared assignment operator taking const S&. Putting the two together, the compiler interprets s = {3, 4} as s.operator=(S{3, 4})

The same happens with std::array.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
  • But does this really explain that you can write `std::array a = {0,1,2,3,4,5,6,7,8,9}; a = {1};`? (And that then `a[0]` is `1` and `a[1]` ... `a[9]` is `0`?). And the `std::array a2 = {0}; // elements all have value 0` of the book is also misleading. `std::array a2 = {1};` would result in the first element to be `1` and all remaining to be `0`. – t.niese Feb 17 '19 at 16:45
  • So, the book is wrong then ? or this feature got added later ? – bornfree Feb 17 '19 at 16:47
  • @t.niese *"But does this really explain..."* Yes, I believe it does. What specifically do you feel remains unclear? – Igor Tandetnik Feb 17 '19 at 17:21
  • @bornfree I'm not familiar with this particular book. If in fact it says that `a2 = {0};` should not be accepted by a C++11-conforming compiler, then it's mistaken, in my opinion. – Igor Tandetnik Feb 17 '19 at 17:23
  • 1
    Before CWG1270 the book was technically correct for the wrong reason (initializing a `std::array` with `{0}` depends on brace elision, which was not allowed in that context). – T.C. Feb 17 '19 at 18:03