Valid tive C ++ clause 11

Source: Internet
Author: User

Valid tive C ++ clause 11
Handle "self-assignment" in operator ="

What is self-assignment? Obviously. The value is assigned to the user. The following code is self-assignment:

Class Widget {public: Widget & operator = (const Widget & rhs) {delete p; p = new int (ths. p); return * this;} int * p;}; Widget w1, w2; w1 = w2; w1 = w1; // assign values by yourself.

As shown in the code above, the operation of deleting the data of the user will occur during self-assignment, which is very dangerous. Because p becomes a wild pointer.

To prevent the preceding errors, you can perform a "self-test". If you find that the error is self-assigned, the system returns the error directly.
The following code:

Class Widget {public: Widget & operator = (const Widget & rhs) {if (this = & rhs) // self-test return * this; delete p; p = new int (rhs. p); return * this;} int * p ;};

However, the above Code has another defect, that is, once a new space fails, p will still become a wild pointer.
Therefore, you can save the original data first, and replace the data after the new is successful;
Modify the code again as follows:

Class Widget {public: Widget & operator = (const Widget & rhs) {int tmp = p; // record the original memory p = new int (rhs. p); delete tmp; // release the original memory return * this;} int * p ;};

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.