2 value in one variable (const and const_cast) c++ [closed]

牧云@^-^@ 提交于 2019-12-25 06:43:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!