c++ - 为什么当 std::initializer_list 被用作赋值参数时它不是引用类型?

标签 c++ c++11 vector stl

以下内容来自 C++ Primer 第五版(第 564 页):

As one example, in addition to the copy- and move-assignment operators, the library vector class defines a third assignment operator that takes a braced list of elements (§ 9.2.5, p. 337). We can use this operator as follows:

vector<string> v;
v = {"a", "an", "the"};

We can add this operator to our StrVec class (§ 13.5, p. 526) as well:

class StrVec {
public:
    StrVec &operator=(std::initializer_list<std::string>);
    //                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
};

在阅读时,我注意到这里使用的参数是一个值,而不是我预期的引用。所以我找到了 std::vector 的 STL 库代码。下面是我从文件 STL_vector.h 中找到的内容:

  /**
   *  @brief  Builds a %vector from an initializer list.
   *  @param  __l  An initializer_list.
   *  @param  __a  An allocator.
   *
   *  Create a %vector consisting of copies of the elements in the
   *  initializer_list @a __l.
   *
   *  This will call the element type's copy constructor N times
   *  (where N is @a __l.size()) and do no memory reallocation.
   */
  vector(initializer_list<value_type> __l,
     const allocator_type& __a = allocator_type())
  : _Base(__a)
  {
_M_range_initialize(__l.begin(), __l.end(),
            random_access_iterator_tag());
  }

似乎用于 std::vector 的参数也是一个值,而不是像本书中那样的引用。但为什么? 使用引用不是更有效率吗?

最佳答案

如果我们查看 std::initializer_list 的引用它说:

Initializer lists may be implemented as a pair of pointers or pointer and length. Copying a std::initializer_list does not copy the underlying objects.

这给了你一个关于为什么它是按值传递的强烈提示,因为复制一对指针或一个指针和一个长度并不是很昂贵。引用实际上来自 draft standard 18.9 初始化程序列表 2 段。

如果我们看一下 earlier proposals 中的一个我们发现相同的推理:

Note that an initializer_list is a small object (probably two words), so passing it by value makes sense. Passing by value also simplifies inlining of begin() and end() and constant expression evaluation of size().

关于c++ - 为什么当 std::initializer_list 被用作赋值参数时它不是引用类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21104923/

相关文章:

c++ - 相同的地址位置如何给出两个不同的值?

c++ - 在函数指针之间转换

C++:value_type 与 make_pair,哪个更快用于 map 插入?

c++ - 不能在数组上使用 .begin() 或 .end()

c++ - 按值传递对象时出现断言错误——这是我的复制构造函数?

c++ - 来自 QDateTime 的 QT 的 fromTime_t 不起作用

c++ - 为什么重载决策不选择第一个函数?

c++ - C++17 异常说明符类型系统将如何工作?

c++ - 基于列对二维 vector 数组进行排序

c++ - 为什么 vector 在元素数量少时优于列表?