Item 10 - Have assignment operators return a reference to *this.
One of the interesting things about assignemnts is that you can chain them together:
Also interesting is that assignment is right-associative, so the above assignment chain is parsed like this:
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 you classes:
This convention applies to all assignment operators, not just the standard form shown above. Hence:
This is only a conventionl 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 the STL.
Things to Remember
Have assignment operators return a reference to
*this
PreviousItem 9 - Never call virtual functions during construction or destruction.NextItem 11 - Handle assignment to self in operator=.
Last updated