*this not returned in copy assignment operator
operator= method does not return a
pointer to the current object
Description
This defect occurs when assignment operators
such as operator= and operator+= do
not return a reference to *this, where this is
a pointer to the current object. If the operator= method
does not return *this, it means that a=b or a.operator=(b) is
not returning the assignee a following the assignment.
For instance:
The operator returns its parameter instead of a reference to the current object.
That is, the operator has a form
MyClass & operator=(const MyClass & rhs) { ... return rhs; }instead ofMyClass & operator=(const MyClass & rhs) { ... return *this; }.The operator returns by value and not reference.
That is, the operator has a form
MyClass operator=(const MyClass & rhs) { ... return *this; }instead ofMyClass & operator=(const MyClass & rhs) { ... return *this; }.
Risk
Users typically expect object assignments to behave like assignments
between built-in types and expect an assignment to return the assignee.
For instance, a right-associative chained assignment a=b=c requires
that b=c return the assignee b following
the assignment. If your assignment operator behaves differently, users
of your class can face unexpected consequences.
The unexpected consequences occur when the assignment is part of another statement. For instance:
If the
operator=returns its parameter instead of a reference to the current object, the assignmenta=breturnsbinstead ofa. If theoperator=performs a partial assignment of data members, following an assignmenta=b, the data members ofaandbare different. If you or another user of your class read the data members of the return value and expect the data members ofa, you might have unexpected results. For an example, see Return Value of operator= Same as Argument.If the
operator=method returns*thisby value and not reference, a copy of*thisis returned. If you expect to modify the result of the assignment using a statement such as(a=b).modifyValue(), you modify a copy ofainstead ofaitself.
Fix
Return *this from your assignment operators.
Examples
Result Information
| Group: Object oriented |
| Language: C++ |
| Default: Off |
Command-Line Syntax: RETURN_NOT_REF_TO_THIS |
| Impact: Low |
Version History
Introduced in R2015b
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)