Const_cast not working C ++?

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 conclusion was:

 k before=1 k after=1 

why doesn't const cast work here?

+4
source share
3 answers

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.

+2
source

const_cast causes undefined behavior if you drop const and then write to the value. Doing nothing valid behavior, as you saw here.

In your specific example, it probably happened that the compiler sees that k declared as the storage class const , knows that it cannot (legally) change and replaces

 cout<<"k after="<<k<<endl; 

with

 cout<<"k after="<<1<<endl; 

If you turn off optimization, you may (or may not) get a different result.

The very reason that dropping const causes undefined behavior is because the compiler is free to perform such optimizations. If const variables can be freely added to non- const variables and written to, then const will be completely meaningless for the compiler.

+12
source

What you do is Undefined Behavior . You cannot try to change the const variable

+4
source

Source: https://habr.com/ru/post/1392221/


All Articles