Skip to content
Quantoros

What does constcast actually guarantee, and when is it undefined?

C++Level: IntermediateCasting & Type Conversions

What does const_cast actually guarantee, and when is it undefined?

Hints
  • Identify types, object lifetimes and compile-time decisions.
  • Separate language guarantees from a particular compiler's behavior.

Answer

const_cast: Removing or Adding const

:Source: src/casting/const-cast

The const_cast operator adds or removes const (or volatile) qualifiers from a pointer or reference. This is the only C++ cast that can modify cv-qualifiers. The primary use case is interfacing with legacy C APIs or older C++ code that lacks proper const-correctness. Modifying a truly const object through const_cast results in undefined behavior, so it should only be used when you are certain the underlying object was not originally declared as const.

#include <iostream>

void legacy_api(int &x) {
  const_cast<int &>(x) = 0;  // Remove const to modify
}

int main(int argc, char *argv[]) {
  int x = 123;
  legacy_api(x);
  std::cout << x << "\n";  // Output: 0
}

note:

Using const_cast to modify an object that was originally declared const is undefined behavior. Only use it when you know the underlying object is non-const.

Answer section

Source and licence: C/C++ Interview Cheatsheet — Chang Ning Tsai · MIT

Related questions