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 ;};