自 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/