C++11:std::initializer_list 是否存储匿名数组?它是可变的吗?
C++11: Does std::initializer_list store anonymous array? Is it mutable?
C++ 标准是否规定 std::initializer_list<T>
是对本地匿名数组的引用?如果它说,那么我们永远不应该 return 这样的对象。标准中的任何部分都这样说吗?
另一个问题,std::initializer_list<T>
的底层对象是可变的吗?我尝试修改它:
#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;
}
但编译时出现错误:错误:只读引用的增量'e'
如果我想更改 initializer_list 中的值,我该如何解决?
来自 cppreference 文章
Copying a std::initializer_list does not copy the underlying objects.
来自[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.
这应该可以回答您的两个问题:复制 initializer_list
不会复制底层元素,而底层元素是 const
,因此您无法修改它们。
How can I fix it if I wish to change the value inside the initializer_list
?
不要使用 initializer_list<int>
。使用 array<int, 3>
或 vector<int>
或其他容器。
C++ 标准是否规定 std::initializer_list<T>
是对本地匿名数组的引用?如果它说,那么我们永远不应该 return 这样的对象。标准中的任何部分都这样说吗?
另一个问题,std::initializer_list<T>
的底层对象是可变的吗?我尝试修改它:
#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;
}
但编译时出现错误:错误:只读引用的增量'e'
如果我想更改 initializer_list 中的值,我该如何解决?
来自 cppreference 文章
Copying a std::initializer_list does not copy the underlying objects.
来自[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.
这应该可以回答您的两个问题:复制 initializer_list
不会复制底层元素,而底层元素是 const
,因此您无法修改它们。
How can I fix it if I wish to change the value inside the
initializer_list
?
不要使用 initializer_list<int>
。使用 array<int, 3>
或 vector<int>
或其他容器。