C++11: Does std::initializer_list store anonymous array? Is it mutable?

天涯浪子 提交于 2019-12-12 03:44:17

问题


Does the C++ standard say that std::initializer_list<T> is a reference to a local anonymous array? If it says, then we should never return such an object. Any section in the standard say so?

Another question, are the underlying objects of a std::initializer_list<T> mutable? I tried to modify it:

#include <initializer_list>
int main()
{
    auto a1={1,2,3};
    auto a2=a1;//copy or reference?
    for(auto& e:a1)
        ++e;//error
    for(auto& e:a2)
        cout<<e;
    return 0;
}

But compiled with error : error: increment of read-only reference 'e'

How can I fix it if I wish to change the value inside the initializer_list?


回答1:


From [dcl.init.list]:

An object of type std::initializer_list<E> is constructed from an initializer list as if the implementation allocated a temporary array of N elements of type const E, where N is the number of elements in the initializer list. Each element of that array is copy-initialized with the corresponding element of the initializer list, and the std::initializer_list<E> object is constructed to refer to that array.

That should answer both of your questions: copying the initializer_list doesn't copy the underlying elements, and the underlying elements are const so you cannot modify them.

How can I fix it if I wish to change the value inside the initializer_list?

Don't use an initializer_list<int>. Use an array<int, 3> or vector<int> or some other container.




回答2:


From the cppreference article

Copying a std::initializer_list does not copy the underlying objects.


来源:https://stackoverflow.com/questions/37738868/c11-does-stdinitializer-list-store-anonymous-array-is-it-mutable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!