const_cast: same address but different value? [duplicate]

女生的网名这么多〃 提交于 2019-12-31 04:47:03

问题


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

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