问题
New to C++ and learning the const_cast — get really confused by the code below:
int main(){
const int j = 1;
int * p = (int *)(&j);
cout << j << ' ' << *p << endl;
cout << &j << ' ' << p << endl;
*p = 2;
cout << j << ' ' << *p << endl;
cout << &j << ' ' << p << endl;
const int k = 1;
int * q = const_cast<int*>(&k);
cout << k << ' ' << *q << endl;
cout << &k << ' ' << q << endl;
*q = 2;
cout << k << ' ' << *q << endl;
cout << &k << ' ' << q << endl;
return 0;
}
The outputs are
1 1
00A2FD9C 00A2FD9C
1 2
00A2FD9C 00A2FD9C
1 1
00A2FD84 00A2FD84
1 2
00A2FD84 00A2FD84
Could anyone tell me why the addresses (&i and p, or &j and q) are the same, but there values (i and *p, or j and *q) are different? I am using Visual Studio 2013RC.
回答1:
That happens because the compiler can assume a const variable won't change, and hence when your code refers to it, the compiler assumes that using the variable value, or the original value at initialization won't matter, it shoudn't change behavior, so it compiles to what is faster to execute, just using constant 1
without referring to memory locations.
回答2:
Using const_cast<T*>(obj)
to cast away constness and modifying the object is undefined behavior if obj
started its life as a constant. In your example you tell the compiler that j
isn't going to change and the compiler just replaces all uses of j
to become uses of 1
, instead. You then break the promise and the code the compiler generated won't pay any attention to you anymore and, instead, does what it pleases.
来源:https://stackoverflow.com/questions/20938920/const-cast-same-address-but-different-value