C ++ 11:std :: initializer_list是否存储匿名数组?是可变的吗? [英] C++11: Does std::initializer_list store anonymous array? Is it mutable?

查看:249
本文介绍了C ++ 11:std :: initializer_list是否存储匿名数组?是可变的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++标准是否表示​​ std :: initializer_list< T> 是对本地匿名数组的引用?如果说,那么我们不应该返回这样的对象。标准中的任何部分都这么说?

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?

另一个问题是 std :: initializer_list< T> mutable?我试图修改它:

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;
}

但编译时带有错误:error:

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

如果我想更改initializer_list中的值,该如何解决?

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

推荐答案

从[dcl.init.list]:

From [dcl.init.list]:


类型为 std :: initializer_list< E> 从初始化器列表构造,如同实现
分配 N 类型<$ c的元素的临时数组$ c> const E ,其中 N
初始化程序列表中的元素数。该数组的每个元素都用初始化器
list的相应元素进行复制初始化,并且 std :: initializer_list< E> 对象被构造为引用该数组。

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 ,因此您无法修改它们。

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.


如果我想更改 initializer_list

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

不要使用 initializer_list< int> 。使用数组 向量< int> 或其他容器。

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

这篇关于C ++ 11:std :: initializer_list是否存储匿名数组?是可变的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆