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

标签 c++ c++11 stl 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 的数据被移动到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 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++ - std::initializer_list 的底层结构是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16894566/

相关文章:

c++ - 按返回类型重载

c++ - 如何使用此 OpenMP 关键部分避免此原始指针?

c++ - 重新检查时指针属性发生变化

c++ - 加号/减号是否国际化?

c++ - STL字符串比较方法与手动编写的方法之间存在巨大的时间差异

c++ - 与多组件 key 的快速部分匹配

c++ - Gstreamer Textoverlay 未更新

c++ - 模板成员默认初始化

c++ - 在 C++ 中编译 opencv

C++使用删除函数报错