问题
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 ofN
elements of typeconst E
, whereN
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 thestd::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