The default copy assignment operator, provided by the compiler if such an operator is not provided by the developer, simply does memberwise assignment of data members and base classes. This could well lead to self-assignment corrupting the state of the object. The chances are that pointers are deleted and then assigned to themselves. To prevent this, the new object state could be built in local variables before being assigned to the data members. However, this could be very inefficient. A better approach is to test for self-assignment (by testing this
against the value of the argument passed to the assignment operator) and then do nothing.
Non-Compliant Code Example
Compliant Solution
if (this != &s) { ... }
Priority: P2 Level: L3
Allowing a copy assignment operator to corrupt an object could lead to undefined behavior.
Component |
Value |
---|---|
Severity |
1 (low) |
Likelihood |
2 (probable) |
Remediation cost |
1 (high) |
References
- Henricson 97 Rule 5.12 Copy assignment operators should be protected from doing destructive actions if an object is assigned to itself