簡體   English   中英

復制賦值運算符中的值傳遞與引用傳遞

[英]Pass by value vs. pass by reference in copy assignment operator

首先,有一個類似的流行帖子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;
}

它不使用復制構造函數。

如果有多個成員,您的賦值運算符不是異常安全的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM