Main Content

C++ reference type qualified with const or volatile

Reference type declared with a redundant const or volatile qualifier

Description

This defect occurs when a variable with reference type is declared with the const or volatile qualifier, for instance:

char &const c;

Risk

The C++14 Standard states that const or volatile qualified references are ill formed (unless they are introduced through a typedef, in which case they are ignored). For instance, a reference to one variable cannot be made to refer to another variable. Therefore, using the const qualifier is not required for a variable with a reference type.

Often the use of these qualifiers indicate a coding error. For instance, you meant to declare a reference to a const-qualified type:

char const &c;
but instead declared a const-qualified reference:
char &const c;
If your compiler does not detect the error, you can see unexpected results. For instance, you might expect c to be immutable but see a different value of c compared to its value at declaration.

Fix

See if the const or volatile qualifier is incorrectly placed. For instance, see if you wanted to refer to a const-qualified type and entered:

char &const c;
instead of:
char const &c;
If the qualifier is incorrectly placed, fix the error. Place the const or volatilequalifier before the & operator. Otherwise, remove the redundant qualifier.

Examples

expand all

int func (int &const iRef) {
    iRef++;
    return iRef%2;
}

In this example, iRef is a const-qualified reference type. Since iRef cannot refer to another variable, the const qualifier is redundant.

Correction — Remove const Qualifier

Remove the redundant const qualifier. Since iRef is modified in func, it is not meant to refer to a const-qualified variable. Moving the const qualifier before & will cause a compilation error.

int func (int &iRef) {
    iRef++;
    return iRef%2;
}
Correction — Fix Placement of const Qualifier

If you do not identify to modify iRef in func, declare iRef as a reference to a const-qualified variable. Place the const qualifier before the & operator. Make sure you do not modify iRef in func.

int func (int const &iRef) {
    return (iRef+1)%2;
}

Result Information

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

Version History

Introduced in R2019a