更改 const_cast 的值 ptr/ref 不会更改原始对象值?

change the value of const_cast ptr/ref doesn't change the original object value?

我发现一个奇怪的问题,即在更改 const_cast ptr/ref 对象值后,同一地址具有不同的值。

#include <iostream>
using namespace std;

int main(void){
    const auto i=123;
    auto &ref2i=i; auto ptr2i=&i;

    auto pp=const_cast<int*>(ptr2i); *pp=456;
    cout<<&i<<" with value "<<i<<endl;
    cout<<pp<<" with value "<<*pp<<endl;
    cout<<ptr2i<<" with value "<<*ptr2i<<endl;

    auto &rr=const_cast<int&>(ref2i); rr=789;
    cout<<i<<endl;
    cout<<ref2i<<endl;
    cout<<rr<<endl;
}

这到底是怎么回事?

https://paiza.io/projects/HyLGbHxD2khynpclDWJnvA?language=cpp

输出:

0x7ffc1b0e8b54 with value 123
0x7ffc1b0e8b54 with value 456
0x7ffc1b0e8b54 with value 456
123
789
789

如果你拼出 ptr2i 的类型,你会得到:

const int * ptr2i = &i;  // since i is const

现在你可以 const_cast 这个 const int * 到一个 int *:

auto pp = const_cast<int*>(ptr2i);  // ok

但是指向变量 i 的类型为 const int,因此如果您随后尝试修改此指向值:

*pp = 456;  // oops, UB since you are attempting to modify i

您调用了未定义的行为。这可能会导致程序执行任何操作,包括在同一地址显示不同的值。

当您将 const int & 转换为 int & 然后尝试修改它时,同样的限制适用。