Negative tive C ++ (10) returns a reference to this object (retrun * this) when the value assignment operator is overloaded)

Source: Internet
Author: User

Problem focus:

This rule is short, but it is often the place where such details can improve the quality of your code. The Details determine the success or failure. Let's learn the rules that need to be followed when this overload assignment operator is used.

Start with an example: Demo
// Chained value assignment x = y = z = 15; // The above expression is equivalent to x = (y = (z = 15 ));

In order to realize the above chained assignment, the value assignment operator must return a reference pointing to the real parameter on the left of the operator. That is:
Class Widget {public: Widget & operator = (const Widget & rhs) {... return * this ;}};

This can be considered as a Protocol applicable to all assignment-related operations.
Class Widget {public :... widget & operator + = (const Widget & rhs ){.... return * this;} Widget & operator = (const Widget & rhs ){... return * this ;}};

Reasons for using this Protocol: All built-in types and types provided by the standard library, such as string, vector, complex, tr1: shared_ptr, or the type to be provided, are shared. Unless you have a good reason to be unconventional, you should follow suit ..
Conclusion: The overload assignment operator returns a reference to * this of the current object)

References: Objective C ++ 3rd

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.