Versions Compared

Key

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

...

Do not cast away a const qualification to attempt to modify the resulting object. The const qualifier implies that the API designer does not intend for that object to be modified, despite the possibility it may be modifiable. Do not cast away a volatile qualification; the volatile qualifier implies that the API designer intends the object to be accessed in ways unknown to the compiler, and any access of the volatile object results in undefined behavior.

...

oncompliant Code Example

In this noncompliant code example, the function g() is passed a const int &, which is then cast to an int & and modified. Because the value referenced to was previously declared as const, the assignment operation results in undefined behavior.

...

Code Block
bgColor#ccccff
langcpp
void g(int &i) {
  i = 42;
}

void f() {
  int i = 4;
  g(i);
}

Noncompliant Code Example

In this noncompliant code example, a const-qualified method is called which attempts to cache results by casting away the const-qualifier of this. Since s was declared const, the mutation of CachedCalc results in undefined behavior.

...

Code Block
bgColor#ccccff
langcpp
#include <iostream>
 
class S {
  mutable int CachedCalc;
  
  int expensiveCompute() const;
public:
  S() : CachedCalc(0) {}
  
  // ...  
  int Calculate() const {
    if (!CachedCalc) {
      CachedCalc = expensiveCompute();  
    }        
    return CachedCalc;
  }
};

void f() {
  const S s;
  std::cout << s.Calculate() << std::endl;
}

Noncompliant Code Example

In this noncompliant code example, the volatile value s has the volatile qualifier cast away, and an attempt is made to read the value within g(), resulting in undefined behavior.

...