The assignment function of a class string is much more complex than a constructor, and is implemented in four steps:
(1) The first step, check the self assignment. You might think that superfluous, that someone would be stupid enough to write a self assignment statement such as a = a! Not really. However, indirect assignments can still occur, such as
Content Self-assignment
b = A;
...
c = b;
...
A = C;
Address Self Assignment
b = &a;
...
A = *b;
Perhaps some people will say: "Even if there is a value, I can ignore it, a big deal of time to let the object copy themselves, anyway, no mistake!" ”
He's really wrong about it. Take a look at the second step of the delete, after committing suicide can you copy yourself? So, if you find a self assignment, you should terminate the function immediately. Note Do not check the self assignment if statement
if (this = = &other)
Wrong writing becomes
if (*this = other)
(2) The second step is to use Delete to release the original memory resources. If you do not release now, there will be no chance of the future, resulting in memory leaks.
(3) The third step is to allocate a new memory resource and copy the string. Note The function strlen returns a valid string length and does not contain a terminator ' ". The function strcpy is copied together with the '.
(4) The fourth step, which returns a reference to this object, is intended to implement a chained expression such as a = B = c. Be careful not to write return *this error. So is it possible to write return to other? Is the effect not the same?
No! Because we don't know the life period of the parameter other. It is possible that other is a temporary object that disappears immediately after the assignment is over, then return the garbage.
9.7 Lazy ways to handle copy constructors and assignment functions
What if we really don't want to write copy constructors and assignment functions and not allow others to use compiler-generated default functions?
The lazy way is to simply declare copy constructors and assignment functions as private functions without writing code.
For example:
Class A
{ ...
Private
A (const a &a); Private copy Constructors
A & operate = (const a &a); Private Assignment function
};
If someone attempts to write the following procedure:
A B (a); A private copy constructor was invoked
b = A; A private assignment function was invoked
The compiler will point out the error because the outside world cannot manipulate a's private function.
9.8 How to implement the basic functions of a class in a derived class
constructors, destructors, and assignment functions of a base class cannot be inherited by derived classes. If there is an inheritance relationship between classes, the following considerations should be noted when writing the basic function:
The constructor of the U-derived class should call the constructor of the base class in its initialization table.
The destructor of the U base class and derived class should be virtual (that is, add virtual)