2016-02-29 68 views
2

我正在創建一個使用+ =操作的對象。是否應該超載返回參考*this或應該只是返回*this在C++中重載擴展賦值(返回類型)

+1

我不明白問題 –

+1

@bath我正要把這個問題作爲同一個問題的重複來解決。我看到你重新打開了它。你不同意這是重複的嗎?你準備發佈一個史詩般的答案? –

+0

由於擬議副本對於這樣一個尖銳的問題來說過於寬泛,因此我重新開放。 – Bathsheba

回答

3

http://en.cppreference.com/w/cpp/language/operators

那裏你可以找到典型實現

class X 
{ 
public: 
    X& operator+=(const X& rhs) // compound assignment (does not need to be a member, 
    {       // but often is, to modify the private members) 
    /* addition of rhs to *this takes place here */ 
    return *this; // return the result by reference 
    } 

    // friends defined inside class body are inline and are hidden from non-ADL lookup 
    friend X operator+(X lhs,  // passing lhs by value helps optimize chained a+b+c 
        const X& rhs) // otherwise, both parameters may be const references 
    { 
    lhs += rhs; // reuse compound assignment 
    return lhs; // return the result by value (uses move constructor) 
    } 
}; 
2

假設foobarFoo實例。

如果+=沒有返回一個引用,則表達式

foo += bar += bar

將語法無效這將是一個背離內置類型(雖然這是有趣的是,內置類型的這種表達式的行爲未定義,因爲+=不是這種類型的排序點)。

未返回引用也可能導致Foo的複製構造函數更多的使用。

快速回答:返回非const參考。