In the study of C ++ assignment operator functions, the type of return values has been very confusing. Today, we will summarize some results of different return value types:
1. When the return value is null:
<span style="font-size:14px;">void hasptr::operator=(const hasptr& s)</span>
At this time, if there is only one '=' (a = B) operation, then there is no problem, but if there is a chain operation of '=' (a = B = C, the compiler reports an error.
Let's see: a = B = C;
The program runs B = C first;
Because the return value of the function is viod, B = C returns a null value.
This Is A = (B = C), that is, a = NULL. This operation does not exist. Even if it exists, it does not meet our original intention for this operation.
2. When the returned value is the class itself:
<span style="font-size:14px;">hasptr hasptr::operator=(const hasptr& s)</span>
Supports '=' chain operations
If the returned value is the class itself, the process of running this function is:
1. Enter the function and run the operations inside the function.
2. After the operation inside the function is completed, call the copy constructor of the class to copy the object to a new object.
3. Return the newly created object.
The key here is that every time a value assignment operator function is run, a copy constructor is called, which will not only waste time.
If the constructor is not copied to the class, errors may occur.
3. When the return value is a reference
<span style="font-size:14px;">hasptr &hasptr::operator=(const hasptr& s)</span>
This method is the best, that is, it supports chained operations and minimizes the operation time.
Complete code:
<span style="font-size:14px;">hasptr &hasptr::operator=(const hasptr& s){ i = s.i; string *x = new string(*s.ps); delete ps; ps = x; return *this;}</span>