Method not const
Description
This defect occurs when a method that meets these criteria is not marked as a
const
:
The method is not
virtual
.The method does not return pointers or references to nonconst data.
The method does not modify any variables, does not call global functions, and does not call any nonconst member functions.
Risk
If a method in your code satisfies the requirements of being a const
method, then declaring the method as a const
has these advantages:
Objects that are
const
are not allowed to invoke nonconst methods. When you declare a method asconst
, some additional references and objects in your code might be declared asconst
, increasing theconst
correctness of your code.The C++11 standard assumes that
const
methods are free of data races. Using such methods in multiple threads does not require external synchronization, for instance, by usingmutex
objects. Usingconst
method makes concurrent programming convenient.
Not declaring eligible methods a const
makes maintaining the
const
correctness of your code more difficult. Code that is not
const-correct remains vulnerable to unexpected mutation of variables, unexpected
assignments, and inefficient compiler optimization.
Fix
To fix this defect, declare eligible methods as const
. If a
const
overload of the function already exists, consider removing the
nonconst overload.
Examples
Result Information
Group: Good practice |
Language: C++ |
Default: Off |
Command-Line Syntax:
METHOD_NOT_CONST |
Impact: Low |
Version History
Introduced in R2022aSee Also
Variable
shadowing
| Non-initialized
variable
| Write without a further
read
| Improper array
initialization
| Find defects
(-checkers)
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)