C++箴言:讓=返回一個*this的引用

字號:

關(guān)于賦值的一件有意思的事情是你可以把它們穿成一串。
    int x, y, z;
    x = y = z = 15; // chain of assignments
    另一件有意思的事情是賦值是右結(jié)合的,所以,上面的賦值串可以解析成這樣:
    x = (y = (z = 15));
    這里,15 賦給 z,然后將這個賦值的結(jié)果(最新的 z)賦給 y,然后將這個賦值的結(jié)果(最新的 y)賦給 x。
    這里實(shí)現(xiàn)的方法就是讓賦值運(yùn)算符返回一個左側(cè)參數(shù)的引用,而且這就是當(dāng)你為你的類實(shí)現(xiàn)賦值運(yùn)算符時應(yīng)該遵守的約定:
    class Widget {
    public:
     ...
     Widget& operator=(const Widget& rhs) // return type is a reference to
     { // the current class
    ...
    return *this; // return the left-hand object
     }
    ...
    };
    這個約定適用于所有的賦值運(yùn)算符,而不僅僅是上面那樣的標(biāo)準(zhǔn)形式。因此:
    class Widget {
    public:
     ...
     Widget& operator+=(const Widget& rhs) // the convention applies to
     { // +=, -=, *=, etc.
    ...
    return *this;
     }
    Widget& operator=(int rhs) // it applies even if the
     { // operator’s parameter type
    ... // is unconventional
    return *this;
     }
     ...
    };
    這僅僅是一個約定,代碼并不會按照這個意愿編譯。無論如何,這個約定被所有的內(nèi)建類型和標(biāo)準(zhǔn)庫中(或者即將進(jìn)入標(biāo)準(zhǔn)庫)的類型(例如,string,vector,complex,tr1::shared_ptr 等)所遵守。除非你有好的理由作些不同的事情,否則,不要破壞它。
    Things to Remember
    ·讓賦值運(yùn)算符返回一個 *this 的引用。