문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top