c – std :: 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限定的成员函数才能让您访问元素的原因.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...