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

问题描述

在更改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 &并尝试对其进行修改时,存在相同的限制。