C++ Casting away constness


Example

A pointer to a const object can be converted to a pointer to non-const object using the const_cast keyword. Here we use const_cast to call a function that is not const-correct. It only accepts a non-const char* argument even though it never writes through the pointer:

void bad_strlen(char*);
const char* s = "hello, world!";
bad_strlen(s);                    // compile error
bad_strlen(const_cast<char*>(s)); // OK, but it's better to make bad_strlen accept const char*

const_cast to reference type can be used to convert a const-qualified lvalue into a non-const-qualified value.

const_cast is dangerous because it makes it impossible for the C++ type system to prevent you from trying to modify a const object. Doing so results in undefined behavior.

const int x = 123;
int& mutable_x = const_cast<int&>(x);
mutable_x = 456; // may compile, but produces *undefined behavior*