int main(int argc, char *argv[])
{
const int a = 10;
int *p = (int *)&a;
int &r =(int &)(*(&a));
int &r2 = const_cast<int &>(a);
printf("a=%d *p=%d r=%d r2=%d p=%d &a=%d &r=%d &r2=%d\n", a, *p, r, r2, p, &a, &r, &r2);
*p = 11;
printf("a=%d *p=%d r=%d r2=%d p=%d &a=%d &r=%d &r2=%d\n", a, *p, r, r2, p, &a, &r, &r2);
r = 12;
printf("a=%d *p=%d r=%d r2=%d p=%d &a=%d &r=%d &r2=%d" , a, *p, r, r2,p, &a,&r, &r2);
return 0;
}
a=10 *p=10 r=10 r2=10 p=10025000 &a=10025000 &r=10025000 &r2=10025000
a=10 *p=11 r=11 r2=11 p=10025000 &a=10025000 &r=10025000 &r2=10025000a=10 *p=12 r=12 r2=12 p=10025000 &a=10025000 &r=10025000 &r2=10025000
a的内存地址和p所指内存地址、r1,r2的内存地址一样, 但是打印出来a的值和*p,r,r2不同,而*p,r,r2相同
看过一篇文章,通过查看汇编代码,发现 编译器在符号替换时都把常量a 替换成了10,就跟宏替换相似,所以直接用a的地方并不是从内存地址10025000 去取值,而*p,r,r2是去内存地址10025000 取值