Main Content
Copy operation modifying source operand
Copy operation modifies data member of source object
Description
This defect occurs when a copy constructor or copy assignment operator modifies a mutable data member of its source operand.
For instance, this copy constructor A
modifies the data member
m
of its source operand
other
:
class A { mutable int m; public: ... A(const A &other) : m(other.m) { other.m = 0; //Modification of source } }
Risk
A copy operation with a copy constructor (or copy assignment operator):
className new_object = old_object; //Calls copy constructor of className
old_object
to its destination operand
new_object
. After the operation, you expect the destination operand to
be a copy of the unmodified source operand. If the source operand is modified during copy,
this assumption is violated.Fix
Do not modify the source operand in the copy operation.
If you are modifying the source operand in a copy constructor to implement a move operation, use a move constructor instead. Move constructors are defined in the C++11 standard and later.
Examples
Result Information
Group: Object Oriented |
Language: C++ |
Default: On for handwritten code, off for generated code |
Command-Line Syntax:
COPY_MODIFYING_SOURCE |
Impact: Medium |
Version History
Introduced in R2018b
See 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)