One of the new-style C++ casts in C++ (the others are
const_cast is a cast that only lets you "cast const away". (You never need to convert to const -- that conversion is implicit).
In other words,
const_cast<T>(s) is legal only when the implicit conversion from
T exists, ignoring
const_cast is determined at compile-time; if it's illegal, the program won't compile. Other than this limited checking, it's exactly the same as old-style casts or
Some examples (assuming
const T& x = some_T;
T* a = x; // illegal -- &x is "T* const"
T* b = (T*)&x; // OK; old-style cast (anything goes)
X* c = (X*)&x; // OK; old-style cast (anything goes)
T* d = const_cast<T>(x) // OK -- casting away const
x.f(); // OK only if `T::f' is a const method
const_cast<T>(x).f(); // OK
Note, however, that just because something is syntactically legal does not mean it is semantically legal! The ISO C++ standard says you may only modify an object which has had its
const_cast away if it really is non-
const! The implementation is permitted to take great liberties with
const objects (for instance, the implementation might preconstruct simple
const objects and put them in ROM or other memory where the program cannot write!). So a standard program cannot rely on being allowed to cast away
const'ness where it will. Of course, when targetting a particular compiler or platform this requirement may be relaxed. Still, it is undefined behaviour to modify a
const_cast or no
What's modification? For a built-in, it's the obvious: changing the value. For a user defined class, it's calling any method that hasn't been declared "const", or changing any data member which hasn't been declared "mutable". See const and mutable for more on this.