Main Content

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

expand all

typedef const int cint;           
typedef cint& ref_to_cint;       

void func(ref_to_cint refVal, int initVal){
   refVal = initVal;
}

In this example, ref_to_cint is a reference to a const-qualified type. The variable refVal of type ref_to_cint is supposed to be initialized when func is called and not modified subsequently. The modification violates the contract implied by the const qualifier.

Correction — Avoid Modification of const-qualified Reference Types

One possible correction is to avoid the const in the declaration of the reference type.

typedef int& ref_to_int;       

void func(ref_to_int refVal, int initVal){
   refVal = initVal;
}

Result Information

Group: Good practice
Language: C++
Default: Off
Command-Line Syntax: WRITE_REFERENCE_TO_CONST_TYPE
Impact: Low

Version History

Introduced in R2019a