- The key to the assignment operator is the handling of the self-assignment mechanism
You need to consider self-assignment problems when overloading assignment operators, which can cause serious errors.
fred& operator= (const fred& f)
{
// Bad code: Doesn‘t handle self-assignment!
delete p_; // Line #1
p_ = new Wilma(*f.p_); // Line #2
return *this;
There is another error in this example, and if you throw an exception in new, P_ will become a wild pointer. The assignment action code is not intended to make the self-assignment faster. If the current code can handle the self-assignment normally (even if it is slow), then do not say if the statement is added to the assignment operator code. Since the self-assignment is rare, there is no need to make the self-assignment more efficient, and adding unnecessary if judgments can make additional assignment operations incur extra overhead. This is punishing the many to benefit the few.
- Does the assignment operator of a derived class need to call the assignment operator of the base class?
If you create a custom assignment operator, you need to display the assignment operator that calls the base class, because the compiler does not call it automatically, and if you do not create a custom assignment operator, the compiler automatically calls the base class's assignment operator.
C + + Super-faq "Assignment Operators"