Discussion
Once you go const , you (should) never go back. If you cast away const on an object whose original definition really did define it to be const , all bets are off and you are in undefined behavior land. For example, compilers can (and do) put constant data into ROM or write-protected RAM pages. Casting away const from such a truly const object is a punishable lie, and often manifests as a memory fault.Even when it doesn't crash your program, casting away const is a broken promise and doesn't do what many expect. For example, this doesn't allocate a variable-sized array:void Foolish( unsigned int n ) {
const unsigned int size = 1;
const_cast<unsigned int&>(size) = n; // bad: don't do this
char buffer[size]; // will always have size 1
// …
}
C++ has one implicit const_cast , the "conversion of death" from a string literal to char* :char* weird = "Trick or treat?";
The compiler performs a silent const_cast from const char[16] to char* . This was allowed for compatibility with C APIs, but it's a hole in C++'s type system. String literals are ROM-able, and trying to modify the string is liable to cause a memory fault.