C++ reference to const-qualified type with subsequent modification
Reference to const-qualified type is subsequently
modified
Description
This defect occurs when a variable that refers to a
const-qualified type is modified after declaration.
For instance, in this example, refVal has a type const int
&, but its value is modified in a subsequent
statement.
using constIntRefType = const int &;
void func(constIntRefType refVal, int val){
...
refVal = val; //refVal is modified
...
}Risk
The const qualifier on a reference type implies that a variable of
the type is initialized at declaration and will not be subsequently modified.
Compilers can detect modification of references to const-qualified
types as a compilation error. If the compiler does not detect the error, the behavior is
undefined.
Fix
Avoid modification of const-qualified reference types. If the
modification is required, remove the const qualifier from the reference
type declaration.
Examples
Result Information
| Group: Good practice |
| Language: C++ |
| Default: Off |
Command-Line Syntax:
WRITE_REFERENCE_TO_CONST_TYPE |
| Impact: Low |
Version History
Introduced in R2019a
See Also
C++ reference type
qualified with const or volatile | Qualifier removed in conversion | Writing to const qualified object | 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)