Objective C ++ Study Notes-clause 10
Ii. Constructors, Destructors and Assignment Operators
Rule 10: Have assignment operators return a reference to * this
Rule 10: Make operator = return a reference to * this
There is an interesting code chain for assigning values:
Int x, y, z; x = y = z = 15; // chained form of value assignment
In addition, C ++ adopts the right combination law. If brackets are used to represent the priority calculation order, it is like this:
x = ( y = ( z = 15 ) ) ;
In C ++, in order to realize "chained assignment", the value assignment operator must return a real parameter pointing to the left of the operator by reference. (Note: This is the protocol that should be followed when classes implements the value assignment operator)
Class Widget {public :... widget & operator = (const Widget & rhs) // The returned type is a reference {... return * this; // return the object on the left }...};
In addition, this protocol not only applies to the above standard assignment format, but also applies to all assignment-related operations, such as + =,-=, * =, and so on:
Widget& operator+=( const Widget& rhs ){ ... return *this;}
However, it should be noted that this is only an agreement and is not mandatory. If you do not follow it, the code can be compiled by the same way. However, this protocol is shared by all built-in and standard library types, such as string, vector, complex, trl: shared_ptr.
So unless you have enough reason to make a different choice, you should start from the crowd.
☆Remember
The assignment (assign value) operator returns a reference to * this.
* *********************************** Please specify the source: bytes ********************************************