"Effective C + +" study notes-clause 10

Source: Internet
Author: User

*************************************** Reprint Please specify the Source: Http://blog.csdn.net/lttree ********************************************



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



With regard to assignment, there is a very interesting chain code:

int x,y,z;x = y = z = n;    Chained form of assignment

Moreover,C + + adopts right associative law, if you use parentheses to represent the order of precedence, this is the case:

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


in C + +, in order to implement "chained assignment", the assignment operator must return a reference to the left argument of the operator. (Note that this is the protocol that classes should follow when implementing the assignment operator )

<span style= "FONT-SIZE:14PX;" >class Widget  {public:    ...    widget& operator= (const widget& RHS) <span style= "WHITE-SPACE:PRE;" ></span>//return type is a reference    {        ...        return* this;<span style= "WHITE-SPACE:PRE;" ></span>//return to left object    }    ...}; </span>

and this Protocol applies not only to the above standard assignment form, but also to all assignment-related operations , such as + =,-=, *=, etc.:

widget& operator+= (const widget& RHS) {    ...    return *this;}

However,Note that this is only an agreement and is not mandatory, and if you do not follow it, the code can be compiled. However, this agreement is adhered to by all built-in types and standard library types, such as String, vector, complex,trl::shared_ptr, etc.

So unless there's enough reason to be different, it's a herd.


☆ Please remember

Enables the assignment (Assignment) operator to return a reference to *this.




*************************************** Reprint Please specify the Source: Http://blog.csdn.net/lttree ********************************************

"Effective C + +" study notes-clause 10

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.