c++ - const_cast 的奇怪行为

标签 c++ pointers casting

<分区>

我知道使用 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

最佳答案

该程序具有未定义的行为,因为您不能更改 const 对象。

来自 C++ 标准

4 Certain other operations are described in this International Standard as undefined (for example, the effect of attempting to modify a const object). [ Note: This International Standard imposes no requirements on the behavior of programs that contain undefined behavior. —end note ]

关于c++ - const_cast 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22391423/

相关文章:

c++ - 如何在 C++ 中将 const FB::variant& 转换为用户定义的类?

SQL Cast 古怪之处

c++ - 无法将整数分配给动态分配的二维数组

c++ - 位域元素的默认值

C++ 错误 : no matching function for call to 'regex_match()'

pointers - Golang 基础结构和 new() 关键字

c - 字符串指针的子字符串指针

c++ - 我应该如何使用 std::map<> 聚合/组合存储在数组 C++ 中的数据?

通过在 C 中打印指针数组中的字符串元素来转换错误

java - OOP:向上转换与直接实例化