The const_cast operator (C++ only)
A const_cast operator is used to add or remove a const
or volatile
modifier
to or from a type.
Type and the type of expression may only differ with
respect to their const
and volatile
qualifiers.
Their cast is resolved at compile time. A single const_cast
expression
may add or remove any number of const
or volatile
modifiers.
The result of a const_cast
expression is an rvalue
unless Type is a reference type. In this case, the result is
an lvalue.
Types cannot be defined within const_cast
.
The following demonstrates the use of the const_cast
operator:
#include <iostream>
using namespace std;
void f(int* p) {
cout << *p << endl;
}
int main(void) {
const int a = 10;
const int* b = &a;
// Function f() expects int*, not const int*
// f(b);
int* c = const_cast<int*>(b);
f(c);
// Lvalue is const
// *b = 20;
// Undefined behavior
// *c = 30;
int a1 = 40;
const int* b1 = &a1;
int* c1 = const_cast<int*>(b1);
// Integer a1, the object referred to by c1, has
// not been declared const
*c1 = 50;
return 0;
}
The compiler will not allow the function call f(b)
.
Function f()
expects a pointer to an int
,
not a const int
. The statement int* c = const_cast<int>(b)
returns
a pointer c
that refers to a
without
the const
qualification of a
. This
process of using const_cast
to remove the const
qualification
of an object is called casting away constness. Consequently
the compiler will allow the function call f(c)
.The compiler would not allow the assignment *b = 20
because b
points
to an object of type const int
. The compiler will
allow the *c = 30
, but the behavior of this statement
is undefined. If you cast away the constness of an object that has
been explicitly declared as const
, and attempt to
modify it, the results are undefined.
However, if you cast away the constness of an object that has not
been explicitly declared as const
, you can modify
it safely. In the above example, the object referred to by b1
has
not been declared const
, but you cannot modify this
object through b1
. You may cast away the constness
of b1
and modify the value to which it refers.