在 C++ 中删除 constness 后的奇怪输出

Strange output after cast removing constness in C++

在遇到一些转换和 const 问题后,我在一个非常小的代码片段中简化了我的问题:

#include <iostream>
using namespace std;

int main()
{
    const int a = 2;
    
    const int* p = &a;
    int* p_bis = (int*)p;
    
    *p_bis = 42;

    
    printf("\na     = %d", a);
    printf("\n&a    = %p\n", &a);

    printf("\np     = %p", p);
    printf("\n*p    = %d\n", *p);

    printf("\np_bis = %p", p_bis);
    printf("\n*p_bis= %d", *p_bis);
}

在 C++17 中编译后,得到以下输出:

a     = 2                                                                                                                                                                           
&a    = 0x7ffe9924d19c                                                                                                                                                              
                                                                                                                                                                                    
p     = 0x7ffe9924d19c                                                                                                                                                              
*p    = 42                                                                                                                                                                          
                                                                                                                                                                                    
p_bis = 0x7ffe9924d19c                                                                                                                                                              
*p_bis= 42

我知道 int* p_bis = (int*)p; 行很脏,因为我进行了 C 转换而不是干净的 C++ 转换,而且我删除了转换中的常量。但是我不明白的是如何在同一个地址 0x7ffe9924d19c 有 2 个值。难道只是一些未定义的行为,没有别的需要理解的吗?

虽然将 const 指针转换为非 const 指针是完全有效的,但通过该指针修改数据也是有效的 如果数据最初没有定义为const,如果数据最初定义为const(这是你的情况),那么这样做是无效的。更改定义为 const 的变量的值(即使通过间接)是 未定义的行为

以上内容适用于 C 和 C++ 的任何版本。