Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Do not attempt to cv-qualify a reference type as it can result in undefined behavior. A conforming compiler is required to issue a diagnostic message. However, if the compiler does not emit a fatal diagnostic, the program may produce surprising results, such as allowing the character referenced by p to be mutated.

Noncompliant Code Example

In this noncompliant code example, a const-qualified reference to a char is formed instead of a reference to a const-qualified char, resulting in undefined behavior:

Code Block
bgColor#ffcccc
langcpp
#include <iostream>
 
void f(char c) {
  char &const p = c;
  p = 'p';
  std::cout << c << std::endl;
}

Implementation Details

With Microsoft Visual Studio 2013, this code compiles successfully with a warning diagnostic (warning C4227: anachronism used : qualifiers on reference are ignored) and outputs:

...

Code Block
error: 'const' qualifier may not be applied to a reference

Compliant Solution

This compliant solution assumes the programmer intended for the previous example to fail to compile due to attempting to modify a const-qualified char reference:

Code Block
bgColor#ccccff
langcpp
#include <iostream>
 
void f(char c) {
  const char &p = c;
  p = 'p'; // error, read-only variable is not assignable
  std::cout << c << std::endl;
}

Risk Assessment

const and volatile reference types may result in undefined behavior instead of a fatal diagnostic, causing unexpected values to be stored and leading to possible data integrity violations.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

DCL33-CPP

Low

Unlikely

Low

P3

L3

Automated Detection

Tool

Version

Checker

Description

PRQA QA-C++

Include Page
PRQA QA-C++_V
PRQA QA-C++_V

14

 
Clang
Include Page
Clang_V
Clang_V
  

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Bibliography

[ISO/IEC 14882-2014]8.3.2, "References"
[Dewhurst 02]Gotcha #5, "Misunderstanding References"

...