const_cast usually used when / if you get a const pointer to an object that was not originally defined as const . If (as in your case) the object was originally defined as const , an attempt to modify it causes undefined behavior. Without const_cast compiler will not even let you try to do this (the code will not compile).
The cast, however, tells the compiler that you are sure that you know what you are doing, and that it is really safe, so the compiler just needs to shut up and do what you told it, instead of giving error / warning messages, for example usually can happen. Unfortunately, in this case, what you are doing is not very safe, but since you told the compiler to shut up and do this, you will not receive any warnings about this (at least with most compilers).
As for what you should do, it all depends on whether your k const is really or not. If you really need to change it, you need to define it as a regular (not const ) variable. If you want to make sure that only a small amount of specific code can change it, you can / can (for one possibility) make it private to a small class:
class my_int { int k; public: my_int() : k(1) {} do_mod() { k = 10; } operator int() { return k; } };
Now do_mod can directly change k . Other code may use the my_int object as if it were an int , but could not change its value - in fact, it acts like an rvalue.
In fairness, it should be noted that if he is really trying to do some kind of casting, another code can change the value of k . As Bjarne said, the C ++ protection mechanism is designed to prevent accidents, not intentional subversive activities.
source share