c++ - 为什么 std::vector 有两个赋值运算符?

标签 c++ c++11 vector copy-and-swap

自 2011 年以来,我们同时拥有复制和移动任务。但是,this answer非常有说服力地指出,对于资源管理类,只需要一个赋值运算符。例如,对于 std::vector,这看起来像

vector& vector::operator=(vector other)
{
  swap(other);
  return*this;
}

这里的重点是参数是按值取值的。这意味着在输入函数体的那一刻,大部分工作已经通过 other 的构造完成(如果可能,通过移动构造函数,否则通过复制构造函数)。因此,这会自动正确地实现复制和移动分配。

如果这是正确的,为什么(根据 this documentation at least )std::vector 没有以这种方式实现?


编辑以解释其工作原理。考虑以下示例中上述代码中的 other 会发生什么

void foo(std::vector<bar> &&x)
{
  auto y=x;             // other is copy constructed
  auto z=std::move(x);  // other is move constructed, no copy is ever made.
  // ...
}

最佳答案

如果元素类型不可复制,或者容器不遵守强异常保证,那么在目标对象有足够容量的情况下,复制赋值运算符可以避免分配:

vector& operator=(vector const& src)
{
    clear();
    reserve(src.size());  // no allocation if capacity() >= src.size()
    uninitialized_copy_n(src.data(), src.size(), dst.data());
    m_size = src.size();
}

关于c++ - 为什么 std::vector 有两个赋值运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33837485/

相关文章:

c++ - 我如何获得 argv[0]?

c++ - 在 C++ char 数组中打印元音

C++11:将 time_point 增加一秒

c++ - 我是否需要知道算法的代码才能利用插入器和移动迭代器?

c++ - 从 vector 到 vector 的过滤操作

r - 如何在 R 中创建零长度的数值向量

c++ - 使用mergesort c++计算 vector 中的反转

c++ - 使用 boost::gil 从内存中读取 JPEG 图像

c++ - 为什么 std::map::operator[] 赋值需要无参数构造函数?

c++ - 将指针分配给 vector