简体   繁体   中英

Assigning a initializer_list to std::array

I am trying to assign a initializer_list to std::array like below:

std::array<int,2> arr = {0,1};
arr = {0,1,2};

Immediately I get an error saying that there is no viable overload for operator=

I know that I can't attempt to assign an initializer list whose size is greater than the array's size but I am just trying to understand how std::array does this.

I tried looking through the code at https://code.woboq.org/gcc/libstdc++-v3/include/std/array.html but I don't see an overloaded operator= there. So how does std::array use the default operator= to flag such attempts as a compiler error. How does the default operator= know to check the size of the initializer_list? Please help me understand this.

If you carefully read the code link you provided you will see this mentioned in the comments @ line 112 -

// No explicit construct/copy/destroy for aggregate type.

std::array is an aggregate type which (whose elements individually) can be initialized using an braced initializer list just like a regular array.

The code @ lines 109, 110

typedef _GLIBCXX_STD_C::__array_traits<_Tp, _Nm> _AT_Type;
typename _AT_Type::_Type                         _M_elems;

defines a regular array on the stack that has size _Nm which is 2 in your case.

So when you assign a braced initializer list to arr, the initializer list is used to create a temporary std::array<int,2> which is then copied into your array using the default assignment operator. This operation would succeed only if the size of the initializer list is less than or equal to 2. When you pass an braced-initializer list with size greater than 2, it gets flagged as an error because it is not possible to construct a std::array<int,2> from a braced list with size greater than 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM