问题
void main() {
const int a = 10;
const int *b = &a;
int *c = const_cast <int*>(b);
*c = 5;
cout<<a<<" "<<*b<<" "<<*c<<endl; //10 5 5
cout<<&a<<" "<<b<<" "<<c<<endl; //same address
cout<<*(int*)&a<<" "<<*&a<<endl; //5 10
}
what makes type cast affected this? where is the value stored?
回答1:
The program has undefined behavior: with the const_cast<int*>(b)
you remove the const
qualifier from an object which actually is const
and the assignment to that object may have arbitrary effect.
The observed effects indicate that the implementation replaced uses of a
with its immutable value while it dereferences b
to determine the value. It could have arbitrary other effect, too, though. For example, a segmentation fault when trying to write a write protected location could be a possible outcome. Well, anything can happen.
来源:https://stackoverflow.com/questions/23314270/2-value-in-one-variable-const-and-const-cast-c