Use of const_cast removes a const qualifier

ID

c.maintainability.const_cast

Severity

low

Remediation Complexity

medium

Remediation Risk

medium

Remediation Effort

medium

Resource

Type Safety

Language

C / C++

Description

const_cast strips the const (or volatile) qualifier from an object. Writing through the result when the underlying object is truly const is undefined behavior, and it signals a design that fights the type system. Prefer keeping the interface const-correct or overloading on constness instead of casting the qualifier away.

Rationale

const_cast strips the const (or volatile) qualifier from an object. Writing through the result when the underlying object is truly const is undefined behavior, and it signals a design that fights the type system. Prefer keeping the interface const-correct or overloading on constness instead of casting the qualifier away.

The following code illustrates the pattern detected by this rule:

void f() {
  // FLAGGED: Use of const_cast removes a const qualifier
  j = const_cast<int *>(i);

  // FLAGGED: Use of const_cast removes a const qualifier
  j = *const_cast<int **>(&i);

  // FLAGGED: Use of const_cast removes a const qualifier
  j = &const_cast<int &>(*i);
}

Remediation

Follow secure coding practices and review the references below for detailed remediation guidance.

Configuration

This detector does not need any configuration.