我知道使用const_cast
通常是个坏主意,但是我正在尝试它并遇到了一个奇怪的行为,即:
两个指针具有相同的地址值,但是当取消引用时,它们给出不同的数据值。
有人能解释一下吗?
代码
#include <iostream>
int main()
{
const int M = 10;
int* MPtr = const_cast<int*>(&M);
(*MPtr)++;
std::cout << "MPtr = " << MPtr << " (*MPtr) = " << (*MPtr) << std::endl;
std::cout << " &M = " << &M << " M = " << M << std::endl;
}
输出
MPtr = 0x7fff9b4b6ce0 (*MPtr) = 11
&M = 0x7fff9b4b6ce0 M = 10
M
是 const,输出行甚至不会检查存储在其地址处的数字是什么。它只是硬编码了“打印10”,因为您允许编译器假定M
总是10。 - Sneftel