Once a C + + expert said: see a C + + programmer is hard enough, let him write an assignment overload function can be seen! In my opinion, this is not an exaggeration. Because it really needs a solid foundation to write the operator= function well, there are a lot of pitfalls.
- Trap one: Don't know how to avoid self-copying
Look at the code first
string& string::operator= (const string& RHS) { if (m_pstr! = NULL) delete [] m_pstr; M_pstr = new char[....]; strcpy (...); return *this;}
This code is not to evade self-assignment, then if the following call, then the consequences are very serious.
String MyStr ("abc"); mystr = mystr;
In the assignment operation, the data is deleted and then strcpy a null value, and the program hangs up immediately.
Therefore, it is necessary to prevent self-duplication at the beginning of the assignment function. The wording is as follows:
string& string::operator= (const string& RHS) { //Prevent self-assignment if (this = = &RHS) return * this; ...}
But some of the books above use the following wording, do not agree.
string& string::operator= (const string& RHS) { //Prevent self-assignment if (*this = = RHS)//This is just judging the content is the same, and can not be judged to be self-assigned!!! return * this; ...}
- Trap two: The type of the return value with what
Among the beginner's groups, there are several versions of the return values that appear:
Version one string string::operator= (const string& RHS) { ... return * this;}
Or
Version two const string& string::operator= (const string& RHS) { ... return * this;}
Or
Version three string* string::operator= (const string& RHS) { ... return this;}
Version one flaw: More than one temporary object generation and copy, affecting program efficiency.
Version two flaw: A variable of a non-const type would be impossible to get its continuous assignment, and the compiler would have an error.
Version three flaw: The consistency of the type when continuous assignment is not maintained violates the practice of programming. Such as
- Trap three: deep copy not Made
Any versions that have not made deep copies are degraded to the default version.
string& string::operator= (const string& RHS) { if (this = = &RHS) return *this; if (m_pstr! = NULL) delete [] m_pstr; M_pstr = Rhs.m_pstr; Shallow copy return *this;}
A trap-heavy C + + assignment overload function operator=