Objective C ++ Study Notes-clause 10

Source: Internet
Author: User

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 ********************************************

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.