Self assignment not tested in operator
Copy assignment operator does not test for self-assignment
Description
This defect occurs when you do not test if the argument to the copy assignment operator of an object is the object itself. Polyspace® does not raise this defect when you implement the copy operator by using the copy and swap idiom.
Risk
Self-assignment causes unnecessary copying. Though it is unlikely that you assign an object to itself, because of aliasing, you or users of your class cannot always detect a self-assignment.
Self-assignment can cause subtle errors if a data member is a pointer and you allocate memory dynamically to the pointer. In your copy assignment operator, you typically perform these steps:
Deallocate the memory originally associated with the pointer.
delete ptr;
Allocate new memory to the pointer. Initialize the new memory location with contents obtained from the operator argument.
ptr = new ptrType(*(opArgument.ptr));
If the argument to the operator, opArgument
,
is the object itself, after your first step, the pointer data member
in the operator argument, opArgument.ptr
, is not
associated with a memory location. *opArgument.ptr
contains
unpredictable values. Therefore, in the second step, you initialize
the new memory location with unpredictable values.
Fix
Test for self-assignment in the copy assignment operator of your class. Only after the test, perform the assignments in the copy assignment operator.
Examples
Result Information
Group: Object oriented |
Language: C++ |
Default: On for handwritten code, off for generated code |
Command-Line Syntax: MISSING_SELF_ASSIGN_TEST |
Impact: Medium |
Version History
Introduced in R2015bSee Also
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)