Clause 11: handle "self-assignment" in operator ="

Source: Internet
Author: User

"Self-assignment" occurs when an object is assigned to itself:

Class Widget {...}; Widget w;... w = w; // assign a value to yourself

Operator =, not only does not have "self-assigned security", but also does not have "exception Security ".

Making operator = "exceptional security" often automatically returns "self-assigned security. Therefore, more and more people do not care about "self-assignment", but focus on "exception Security.

An alternative solution to ensuring that the Code is not only "abnormal security" but "self-assigned security" is to use the so-called copy and swap technology. This technology is closely related to "abnormal security". It is a common and good enough operator = writing method, and its implementation method is:

Class Widget {public:
... Void swap (Widget & rhs); // exchange * this and any rhs data ...}; widget & Widget: operator = (const Widget & rhs) {Widget temp (rhs); // create a copy of rhs data (copy) swap (temp ); // return * this ;}

Another implementation method is:

Widget & Widget: operator = (Widget rhs) // rhs is a replica of the passed object. Note that pass by value {swap (rhs) is passed here ); // return * this ;}

The preceding implementation method is as follows: 1. A certain type of copy assignment operator may be declared as "accepting real parameters by value"; 2. Passing by value may result in a replica.

This method sacrifices clarity. However, moving the copy action from the function body to the "function parameter construction stage" can make the compiler sometimes produce more efficient code.

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.