Item 10: Have assignment operators return a reference to this


Item 10: Have assignment operators return a reference to *this

One of the interesting things about assignments is that you can chain them together:

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

Also interesting is that assignment is right-associative, so the above assignment chain is parsed like this:

 x = (y = (z = 15)); 

Here, 15 is assigned to z, then the result of that assignment (the updated z) is assigned to y, then the result of that assignment (the updated y) is assigned to x.

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

This is only a convention; code that doesn't follow it will compile. However, the convention is followed by all the built-in types as well as by all the types in (or soon to be in see Item54) the standard library (e.g., string, vector, complex, tr1::shared_ptr, etc.). Unless you have a good reason for doing things differently, don't.

Things to Remember

  • Have assignment operators return a reference to *this.




Effective C++ Third Edition 55 Specific Ways to Improve Your Programs and Designs
Effective C++ Third Edition 55 Specific Ways to Improve Your Programs and Designs
ISBN: 321334876
EAN: N/A
Year: 2006
Pages: 102

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net