const 的值在内存中发生了变化,但在输出中没有变化

Value of const changed in the memory but not on the output

我正在尝试编写一个程序来更改 const 变量的值。我知道一开始就不应该这样做,我这样做只是为了了解这是怎么发生的。

我已经阅读过关于此的其他问题,但我不是想知道如何去做,而是想知道为什么它没有出现在我的程序中。这是我写的代码:

int main()
{
    const int a = 5;

    int *pointer_a = const_cast<int*>(&a);

    *pointer_a = 6;

    // Address of a
    std::cout << &a << std::endl;
    // Prints 5 while memory says it is 6
    std::cout << a << std::endl;

    // Address that pointer points too
    std::cout << pointer_a << std::endl;
    // Prints 6
    std::cout << *pointer_a << std::endl;
}

我在调试这个程序时注意到的是 a 内存地址的值实际上得到了更新。它确实将 a 的值从 5 更改为 6

IDE (Visual Studio) 也显示 a 的值为 6 但是当打印到控制台时,它打印 5 .当内存中的当前值为 6 时,为什么会发生这种情况?

修改最初声明为 const 的值是未定义的行为。

https://en.cppreference.com/w/cpp/language/const_cast:

const_cast makes it possible to form a reference or pointer to non-const type that is actually referring to a const object. Modifying a const object through a non-const access path results in undefined behavior.

尝试关闭编译器优化标志(项目属性、C/C++、优化)