In the assignment operator, pay special attention to alias situations. The reason is based on two points. One of them is efficiency. If you can find that you assign values to yourself in the header of the assignment operator, you can return immediately, which saves a lot of work; otherwise, you must implement the entire assignment operation.
Another more important reason is to ensure correctness. A value assignment operator must first release the resource of an object (remove the old value), and then allocate new resources based on the new value. When you assign a value to yourself, releasing old resources will be disastrous, because the old resources will be needed when new resources are allocated.
Let's take a look at the values assigned to the following String object. The value assignment operator does not check the values assigned to itself:
Class string {public: string (const char * value); // For function definitions, see clause 11 //~ String (); // For function definitions, see clause 11 //... string & operator = (const string & RHs); Private: char * Data ;}; // The assignment operator string & string :: operator = (const string & RHs) {Delete [] data; // delete old memory // allocate new memory, copy the value of RHS to data = new char [strlen (RHS. data) + 1]; strcpy (data, RHS. data); return * This; // see item 15}
Now we can know that the solution to the problem is to check the situations that may occur and assign values to ourselves first. If this happens, the system will return immediately. Unfortunately, this kind of check is easy to say, because you must define two objects to be "the same.
The memory address is used to determine whether the object identity is the same. Using this definition, two objects are the same only when they have the same address. This definition is more widely used in C ++ programs, probably because it is easy to implement and computation fast, and using a definition with equal values may not always have these two advantages. Using the definition of equal addresses, a common value assignment operator looks like this:
C & C: Operator = (const C & RHs) {// check if (this = & RHs) return * This ;...}