Search code examples
arraysc++11mutableinitializer-listanonymous

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


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?


Solution

  • 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.