// Check for self-assignment!
if (this == &rhs) // Same object
return *this; // Yes, so skip assignment, and just return *this.
... // Deallocate, allocate new space, copy values...
return *this;
}Or, you can simplify this a bit by doing:
MyClass& MyClass::operator=(const MyClass &rhs) {
// Only do assignment if RHS is a different object from this.
if (this != &rhs) {
... // Deallocate, allocate new space, copy values...
}
return *this;
}Remember that in the comparison, this is a pointer to the object being called, and &rhs is a pointer to the object being passed in as the argument. So, you can see that we avoid the dangers of self-assignment with this check.
In summary, the guidelines for the assignment operator are:
Take a const-reference for the argument (the right-hand side of the assignment).
Return a reference to the left-hand side, to support safe and reasonable operator chaining. (Do this by returning *this.)
Check for self-assignment, by comparing the pointers (this to &rhs).