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_castwith 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 intor reference toconst int, the value doesn't seem to change.const_castwith 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_castwith 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.
const int) is undefined behaviour, this is the reason why 2 and 3 don't work. 1 doesn't have anyconst int, only anintandconst int*that points to it, so it's ok."\n"literal? Thisendlmacro in your snippets make me feel so uncomfortable :)#define endl '\n'in there -- that is strange...