为什么var和*to var在这个const_cast示例中给出了diff值

sau*_*abh 1 c++

检查此示例是否为const的const_cast.我正在使用VC++ 2008来编译它.

#include <iostream>
using namespace std;

void main() {
const int x=0;
int y=90;
int *p = const_cast<int *> (&x);
*p=y;

cout<<" value of x: "<<x<<" addr of x "<<&x<<endl
    <<" and *p : "<<*p<<" and addr p "<<p<<endl;

}
Run Code Online (Sandbox Code Playgroud)

================

输出是

value of x: 0 addr of x 0012FF60
 and *p : 90 and addr p 0012FF60
Run Code Online (Sandbox Code Playgroud)

Sta*_*fan 5

你不应该const_cast一个定义为const的变量.我手边没有标准,但我相当肯定它将这样的操作定义为导致未定义的行为.

有关为什么会导致未定义行为的示例,请考虑将定义为const的内容存储在非易失性存储器(闪存,EEPROM或甚至更不易变的东西)中的MCU.

C++ FAQ Lite中还有更多内容可供阅读.