参数运算符"&"对const变量的结果是什么?

Avi*_*ron 7 c c++ const operators

有人问我怎样才能改变const变量的值.

我明显的回答是"指针!" 但我尝试了下一段代码,我很困惑......

int main()
{
    const int x = 5;
    int *ptr = (int *)(&x); // "Cast away" the const-ness..
    cout << "Value at " << ptr << ":"<< (*ptr) <<endl;
    *ptr = 6;
    cout << "Now the value of "<< ptr << " is: " << (*ptr) <<endl;
    cout << "But the value of x is still " << x <<endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出是:

Value at <some address> :5
Now the value of <same address> is: 6
But the value of x is still 5
Run Code Online (Sandbox Code Playgroud)

现在,我不确定从'&x'返回的是什么,但它绝对不是x的实际地址,因为x的值没有改变!

但总的来说,ptr 确实包含了x的值!那么,究竟是什么呢?

EDIT使用VS2010编译

sep*_*p2k 15

您的程序调用未定义的行为(通过指针写入const变量是未定义的行为),因此任何事情都可能发生.这就是说这就是为什么你得到你在特定实现上看到的行为的最可能的解释:

当你这样做时&x,你确实得到了地址x.当你这样做时*ptr = 6,你会写6到x内存位置.但是当你这样做时cout << x,你实际上并没有从x内存位置读取,因为你的编译器通过x在这里替换为5来优化代码.由于xconst编译器允许这样做,因为没有合法的C++程序中,这样做会改变程序的行为.