You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

Never qualify a reference with const or volatile.

[[Dewhurst 02]] Gotcha #5, "Misunderstanding References" says:

Strangely, it's not illegal to apply a const or volatile qualifier to a type name that is of reference type. Rather than cause an error, the qualifier...can be ignored.

Noncompliant Code Example

char c = 'c';
char &const p = c;
p = 'p';
cout << c << endl;

Implementation Details

On Microsoft Visual C++, this code compiles without incident and outputs:

p

G++ version 4.2.4 refuses to compile the code, complaining:

: error: 'const' qualifiers cannot be applied to 'char&'

Compliant Solution

If constant access is required, instead of using a const reference, one can use a const pointer:

char c = 'c';
char *const p = c;
*p = 'p'; // causes compiler error
cout << c << endl;

Risk Assessment

Const and volatile references may be freely ignored by the compiler, causing unexpected values to be stored and leading to possible data integrity violations.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

DCL33-CPP

low

unlikely

medium

P2

L3

Related Vulnerabilities

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

References

[[Dewhurst 02]] Gotcha #5, "Misunderstanding References"


DCL33-CPP. Ensure that restrict-qualified source and destination pointers in function arguments do not reference overlapping objects&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;02. Declarations and Initialization (DCL)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; DCL35-CPP. Do not invoke a function using a type that does not match the function definition

  • No labels