(CoolPint) wrote in
news: om:
> While I was reading about const_cast, I got curious and wanted to know
> if I could modify a constant variable through a pointer which has been
> "const_cast"ed. Since the pointer would be pointing to the constant
> variable and if I changed the value through the pointer, the constant
> variable should have been modified. Well, that's what I thought until
> I wrote the following and run it.
No. It is your responsibility to ensure that the object that you
const_cast away from really isn't a const object. Any attempt to modify
a const object, through whatever means you can find, is undefined
behaviour.
>
Some in-line comments which will make more sense with the explanation
below:
> #include <iostream>
> using std::cout;
> using std::endl;
> int main ()
> {
> const int i = 0;
> int &j = const_cast<int&>(i);
This refers to the variable i.
> j = 10; // I thought this would change i, but it didn't
> cout << &i << endl; // &i and &j are same as I expected
This has the address of the variable i.
> cout << &j << endl;
> cout << i << endl; // but i is still 0
Since i is declared as const, the compiler can remove the reference to i,
and rewrite this line to effectively be:
cout << 0 << endl;
> cout << j << endl; // and j is 10!
This refers to the variable i.
> int * p = const_cast<int *>(&i);
> *p = 30; // I change i via p
> cout << &i << endl; // I confirm that p is pointing to i!
> cout << p << endl; // I confirm that p is pointing to i
> cout << i << endl; // i is still 0!
> cout << *p << endl; // how can *p be 30 then?
Same logic as above.
>
> return 0;
> }
>
> I am very much confused. &i and &j are same, meaning they refer to the
> same location. p is also pointing to the same location. But then how
> can i still be 0 and j be 10 and i still be 0 and *p 30????
Since you told the compiler that i is a const int 0, anyplace that i is
used, the compiler could optimize the variable access away and replace it
with a literal 0. When you took the address of i, it needs a memory
location, so the compiler is forced to allocate memory for it. (Side
question: if you never cause the address of i to be taken, even
implicitly, is the compiler required to reserve memory space for i, or
can it completely optimize the variable out of existance?)
> Is j allocated new memory space? Is p pointing to a new location?
>
> Can anyone kindly help me figure out what is going on?
>
> BTW, is what I am observing is standard behaviour or particular to my
> compiler (g++ version 3.2.3)?
It's undefined behaviour. The compiler could format your hard drive and
cause monkeys to fly out of your nether regions (OK, from a Standard
point of view it could...).