I have the following code :
const int k=1;
int *p=const_cast<int *>( &k);
cout<<"k before="<<*p<<endl;
*p=10;
*const_cast<int *>( &k)=12;
cout<<"k after="<<k<<endl;
the output was :
k before=1
k after=1
why doesn't const cast work here ?
const_cast
is normally used when/if you receive aconst
pointer to an object that wasn't originally defined asconst
. If (as in your case) the object was originally defined asconst
, attempting to modify it causes undefined behavior. Without theconst_cast
, the compiler won't let you even try to do that (the code won't compile).A cast, however, tells the compiler you're sure you know what you're doing and it's really safe, so the compiler just needs to shut up and do what you told it instead of giving any error/warning messages like it might usually do. Unfortunately, in this case what you're doing is not really safe, but since you've told the compiler to shut up and do it, you won't get any warning about it (at least with most compilers).
As to what you should do, it comes down to deciding whether your
k
is really const or not. If you really need to modify it, then you need to define it as a normal (non-const
) variable. If you want to ensure that only a small amount of specific code can modify it, then you could/can (for one possibility) make it private to a small class:Now,
do_mod
can modifyk
directly. Other code can use amy_int
object as if it were anint
, but can't modify its value -- in essence, it acts like an rvalue.In fairness, I should probably point out that if it really tries by doing some casting, other code can modify the value of
k
. As Bjarne has said, C++'s protection mechanism is intended to prevent accidents, not intentional subversion.