CKTIS / C++
const_cast — changing const and volatile qualifiers
const_cast explicitly changes const and volatile qualifiers in permitted pointer and reference conversions. It does not change the actual object: removing const from an access type does not permit modifying an object that is actually const.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
const_cast<T>(expression)const_cast<T>(expression) changes const and volatile qualifiers in permitted conversions of object pointers, pointers to data members, and object references. It does not change the underlying type, such as converting int* to double*, or convert function pointers or member function pointers.
For a target type T&, the result is an lvalue; for T&&, an xvalue; and for a pointer, a prvalue. If the original pointer points to an object, the result points to that same object. A cast to a reference type refers to the same object. A null object pointer or null pointer to a data member remains null. A non-null pointer to a data member still designates the same member after the cast, not a particular object instance. The cast does not create a modifiable copy of the object.
Removing const from an access type does not remove the object's constness. Attempting to modify an actually const object causes undefined behavior. The cast itself is not such a modification. Accessing a volatile object through a non-volatile glvalue also causes undefined behavior.
In the example, value is not const, so writes through writable and the result of const_cast<int&>(reference) are permitted; the program prints 30. When you control the interface, prefer correct qualifiers over a cast. The supplied site contains an evolving working draft, not a frozen C++23 publication.
Examples
#include <iostream>
int main() {
int value = 10;
const int* view = &value;
int* writable = const_cast<int*>(view);
*writable = 25;
const int& reference = value;
const_cast<int&>(reference) = 30;
std::cout << value << '\n';
}
Result
30
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.