Effective C++ 笔记 —— Item 10: Have assignment operators return a reference to *this.

For this code:

int x, y, z;
x = y = z = 15; // chain of assignments

 

The way this is implemented is that assignment returns a reference to its left-hand argument, and that’s the convention you should follow when you implement assignment operators for your classes:

class Widget 
{
public:
    //...
    Widget& operator=(const Widget& rhs) // return type is a reference to the current class
    {
        //...
        return *this; // return the left-hand object
    }
    //...
};

//This convention applies to all assignment operators, not just the standard form shown above.Hence:

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

 

Things to Remember

  • Have assignment operators return a reference to *this.

 

posted @ 2021-08-30 11:22  MyCPlusPlus  阅读(32)  评论(0编辑  收藏  举报