"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.