加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – std :: initializer_list的底层结构是什么?

发布时间:2020-12-16 07:49:49 所属栏目:百科 来源:网络整理
导读:第一部分 : std :: initializer_list是C 11的一个非常有用的功能,所以我想知道它是如何在标准库中实现的.从我读的here开始,编译器创建一个T类型的数组,并给出指向initializer_list T的指针. 它还声明复制initializer_list将创建一个引用相同数据的新对象:
第一部分 :

std :: initializer_list是C 11的一个非常有用的功能,所以我想知道它是如何在标准库中实现的.从我读的here开始,编译器创建一个T类型的数组,并给出指向initializer_list< T>的指针.

它还声明复制initializer_list将创建一个引用相同数据的新对象:为什么会这样?我猜它也是:

>复制新initializer_list的数据
>将数据的所有权移至新的initializer_list

第二部分 :

从std :: vector构造函数的许多在线引用中只有一个:

vector (initializer_list<value_type> il,const allocator_type& alloc = allocator_type());

(6) initializer list constructor

Constructs a container with a copy of each of the elements in il,in the same order.

我对移动语义还不满意,但是不能将il的数据移动到向量中吗?我不知道std :: vector的深度实现,但它使用了普通的数组IIRC.

解决方法

What is the underlying structure of std::initializer_list?

最有可能的,只是一对指针,或指针和大小. C 11标准第18.9 / 2段甚至在(非规范性)说明中提及:

An object of type initializer_list<E> provides access to an array of objects of type const E. [ Note:
A pair of pointers or a pointer plus a length would be obvious representations for initializer_list.
initializer_list is used to implement initializer lists as specified in 8.5.4. Copying an initializer list does
not copy the underlying elements. —end note ]

此外:

I am not comfortable with move semantics yet,but couldn’t the data of il be moved to the vector?

不,你不能从initializer_list的元素移动,因为initializer_list的元素应该是不可变的(参见上面引用的段落的第一句).这也是为什么只有const限定的成员函数才能让您访问元素的原因.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读