我正在通过访问内存位置来更改const变量的值.为什么不起作用? [英] I'm changing the value of a const variable by accessing the memory location. Why doesn't it work?
问题描述
我正在尝试理解c ++中的 const .我写了以下代码片段:
I am trying to understand const in c++. I wrote this following code snippet:
const int x=5;
int *ptr;
ptr=(int*)&x;
cout<<"address of x="<<&x<<endl;
cout<<"value of ptr="<<ptr<<endl;
*ptr=11;
cout<<"*ptr="<<*ptr<<endl;
cout<<"x="<<x;
输出为
address of x=0x28fef8
address of ptr=0x28fef8
*ptr=11
x=5
由于 ptr 指向 x ,因此我确定* ptr和x的值相同.为什么值不同?我知道 x是const ,但是,我通过执行 * ptr 来更改内存地址中的值.请告诉我我在想什么.
Since ptr is pointing to x, i was sure the value of the *ptr and x would be the same. Why are the values different? I understand that x is const, however, i am changing the value at the memory address by doing *ptr . Please tell me what am i missing.
推荐答案
正式答案(根据C ++语言标准):
未定义的行为.
实际答案(取决于编译器的实现):
使用全局 const int x = 5
,该变量分配在可执行映像的RO-data部分中.
With a global const int x=5
, the variable is allocated in the RO-data section of the executable image.
因此,在运行时执行 * ptr = 11
的结果将是非法的内存访问异常.
The result of executing *ptr=11
will therefore be an illegal memory access exception during runtime.
使用本地 const int x = 5
,该变量分配在可执行映像的(RW)堆栈部分.
With a local const int x=5
, the variable is allocated on the (RW) stack section of the executable image.
但是,由于 x
是常量,因此编译器会将该变量的每个r值引用替换为5.
But since x
is constant, the compiler replaces every r-value reference of this variable with the value of 5.
这篇关于我正在通过访问内存位置来更改const变量的值.为什么不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!