What is const_cast and when is it (rarely) appropriate?
Short answer
const_cast adds or removes const/volatile qualifiers from a pointer or reference.
Advertisement
AModel 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 modifyReal-world example
const_cast bridges to a legacy C API that lacks const, on data known to be mutable.
Likely follow-ups
- When is removing const undefined behavior? | Why is const_cast a code smell?
Related topics