Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is assignment of std::array from braced list of values allowed in c++?

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?

like image 672
bornfree Avatar asked Feb 17 '19 15:02

bornfree


1 Answers

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.

like image 54
Igor Tandetnik Avatar answered Sep 28 '22 17:09

Igor Tandetnik