w****g 发帖数: 206 | 1 运行一下 程序:
int main() {
const int i = 0;
int * j;
cout << "&j=" << &j << endl;
cout << "&i=" << &i << endl;
cout << "j=" << j << endl;
j = const_cast(&i);
*j = 2;
cout << "i=" << i << endl;
cout << "*j=" << *j << endl;
cout << "j=" << j << endl;
cout << "&i=" <<&i <
}
得到结果:
&j=0xbf93a658
&i=0xbf93a65c
j=0
i=0
*j=2
j=0xbf93a65c
&i=0xbf93a65c
这就是说:j 和&i是一样的,但是为什么i和*j不一样呢? |
s*****n 发帖数: 5488 | 2 looks like j is int pointer. and const-cast just removes the const of the
pointer.
【在 w****g 的大作中提到】 : 运行一下 程序: : int main() { : const int i = 0; : int * j; : cout << "&j=" << &j << endl; : cout << "&i=" << &i << endl; : cout << "j=" << j << endl; : j = const_cast(&i); : *j = 2; : cout << "i=" << i << endl;
|
M********5 发帖数: 715 | 3 This is undefined behavior of const_cast. So that's the reason why you need
to take care when you use those cast features.
You can google const_cast undefined behavior. |
r**u 发帖数: 1567 | 4 This doesn't explain his question. Since i & *j points to the same address,
why i = 0 but *j = 2?
【在 s*****n 的大作中提到】 : looks like j is int pointer. and const-cast just removes the const of the : pointer.
|
x***y 发帖数: 633 | 5 change the definition of "const int i = 0" to
"volatile const int = 0", then i will be 2. The reason is due to
optimization, that i will be read from register, not from memory.
【在 w****g 的大作中提到】 : 运行一下 程序: : int main() { : const int i = 0; : int * j; : cout << "&j=" << &j << endl; : cout << "&i=" << &i << endl; : cout << "j=" << j << endl; : j = const_cast(&i); : *j = 2; : cout << "i=" << i << endl;
|
h**k 发帖数: 3368 | 6 volatile关键字会强迫从内存中读取,而不会只返回寄存器中的值。
我觉得是compiler直接优化,把输出i的值的语句中的i直接替换成0,因为i声明成
const变量。
【在 x***y 的大作中提到】 : change the definition of "const int i = 0" to : "volatile const int = 0", then i will be 2. The reason is due to : optimization, that i will be read from register, not from memory.
|
d*********i 发帖数: 628 | |
f****4 发帖数: 1359 | |