• 主页
  • 在复制赋值运算符中按值传递与按引用传递

在复制赋值运算符中按值传递与按引用传递

首先,也是最重要的,有一个类似的流行帖子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/的链接。

accepted和linked页面的状态都是复制赋值运算符的常用实现(从上一个链接复制和粘贴)

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;
}

它不使用复制构造函数。

转载请注明出处:http://www.jxbyjx.net/article/20230525/1999246.html