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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With