c++const-cast

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


I found a weird problem of same address with different values after change const_cast ptr/ref object value.

#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;
}

what the hell is going on?

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

Output:

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

Solution

  • If you spell out the type of ptr2i you get:

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

    Now you can const_cast this const int * to an int *:

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

    But the pointed at variable i has type const int, so if you then try to modify this pointed at value:

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

    you invoke undefined behavior. This can result in a program that does anything, including showing different values at the same address.

    The same restrictions apply when you cast a const int & to an int & and then try to modify it.