检查此示例中的 const_cast of int。 我正在使用 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;
}
================
输出为
value of x: 0 addr of x 0012FF60
and *p : 90 and addr p 0012FF60
最佳答案
你不应该 const_cast 定义为 const 的变量。我手头没有标准,但我相当确定它定义了这样一个导致未定义行为的操作。
关于为什么这会导致未定义行为的示例,请考虑一个 MCU,其中定义为 const 的内容存储在非 volatile 存储器(闪存、EEPROM 或更不易失的东西)中。
在 C++ FAQ Lite 中还有更多内容需要阅读.
关于c++ - 为什么 var 和 * 到 var 在此 const_cast 示例中给出差异值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3204781/