1. 程式人生 > 其它 >Effective C++ 筆記 —— Item 10: Have assignment operators return a reference to *this.

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.