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 typeconst E
. [ Note:
A pair of pointers or a pointer plus a length would be obvIoUs representations forinitializer_list
.
initializer_list
is used to implement initializer lists as specified in 8.5.4. copying aninitializer 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限定的成员函数才能让您访问元素的原因.
原文地址:https://www.jb51.cc/c/115341.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。