第一部分:
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
的数据被移动到vector
?我不知道 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
的原因- 合格的成员函数使您可以访问元素。
关于c++ - std::initializer_list 的底层结构是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16894566/