1

首先,有一个类似的热门帖子What is the copy-and-swap idiom?. 接受的答案具有指向https://web.archive.org/web/20140113221447/http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/的链接。

接受和链接的页面都表明复制赋值运算符的常用实现是(从上一个链接复制和粘贴)

T& T::operator=(T const& x) // x is a reference to the source
{ 
    T tmp(x);          // copy construction of tmp does the hard work
    swap(*this, tmp);  // trade our resources for tmp's
    return *this;      // our (old) resources get destroyed with tmp 
}

但那

T& operator=(T x)    // x is a copy of the source; hard work already done
{
    swap(*this, x);  // trade our resources for x's
    return *this;    // our (old) resources get destroyed with x
}

由于编译器的复制省略优化,更好,或者通常,总是按值传递而不是通过引用传递,然后复制通过引用传递的参数。

我同意第二个选项与第一个选项相同或更好,但并不差,但我很困惑为什么第一个选项一开始就是这样写的。我不明白为什么需要临时变量和交换。

相反,我们不能只做类似的事情:

T& T::operator=(T const& x) // x is a reference to the source
{ 
    this->member_var = x.member_var;
    //if we have to do a deep copy of something, implement that here
    return *this;
}

它不使用复制构造函数。

4

1 回答 1

1

如果有多个成员,您的赋值运算符不是异常安全的:

T& T::operator=(T const& x) 
{ 
    this->member_var1 = x.member_var1; 
    this->member_var2 = x.member_var2; // if an exception occurs here, this->member_var1 will still be changed
    return *this;
}
于 2020-02-28T05:08:13.433 回答