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.
const int
) is undefined behaviour, this is the reason why 2 and 3 don't work. 1 doesn't have anyconst int
, only anint
andconst int*
that points to it, so it's ok. – Microscope"\n"
literal? Thisendl
macro in your snippets make me feel so uncomfortable :) – Hallelujahendl
is not a macro. – Microscope'\n'
ends the line but does not necessarily flush output buffers;std::endl
does both. While the difference is of little significance at the end ofmain()
(where buffers will be flushed regardless), it's a case of "mean what you say, say what you mean". ;-) – Taneshatang*ptr=321;
and see what happens. – Microscopecout << "whatever" << endl;
makes me expectusing namespace std;
or separate using directives somewhere. – Hallelujah#define endl '\n'
in there -- that is strange... – Taneshatang