I understand that const_cast
works with pointers and references.
I'm assuming that the input to const_cast
should be a pointer or reference. I want to know why it doesn't remove the constness if the input is a pointer/reference to a const int
?
The following code works as expected.
const_cast
with multilevel pointersint main() { using std::cout; #define endl '\n' const int * ip = new int(123); const int * ptr = ip; *const_cast<int*>(ptr) = 321; cout << "*ip: " << *ip << endl; // value of *ip is changed to 321 }
But when I try a pointer to
const int
or reference toconst int
, the value doesn't seem to change.const_cast
with reference to const intint main() { using std::cout; #define endl '\n' const int i = 123; const int & ri = i; const_cast<int&>(ri) = 321; cout << "i: " << i << endl; // value in 'i' is 123 }
const_cast
with pointer to const intint main() { using std::cout; #define endl '\n' const int i = 123; const int * ri = &i; *const_cast<int*>(ri) = 321; cout << "i: " << i << endl; // value in 'i' is 123 }
(1) works as expected, but I'm unable to comprehend why (2) & (3) don't work the way I think though the input to the const_cast
is a pointer/reference.
Please help me understand the philosophy behind this. Thanks.