gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:14:59 27 4
gpt4 key购买 nike

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

As one example, in addition to the copy- and move-assignmentoperators, the library vector class defines a third assignmentoperator that takes a braced list of elements (§ 9.2.5, p. 337). Wecan 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com