C++ › Const Correctness

What is const_cast and when is it (rarely) appropriate?

Intermediate

Answer

const_cast adds or removes const/volatile qualifiers from a pointer or reference. Removing const to modify an object that is genuinely const is undefined behavior; const_cast is only safe to remove const you know was added artificially (e.g., interfacing with a legacy non-const API on an object that is actually mutable). It's a code smell to be used sparingly.
void legacy(char* s);
void wrap(const char* s) { legacy(const_cast<char*>(s)); } // only if legacy won't modify
Real-world example const_cast bridges to a legacy C API that lacks const, on data known to be mutable.

Common follow-ups: When is removing const undefined behavior? | Why is const_cast a code smell?