0

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
Larry
  • 155
  • 7
  • 2
    You cannot change value of `const` object, neither with `const_cast` nor anything else. Attempting to do so results in Undefined Behaviour. – Yksisarvinen Sep 11 '20 at 15:16
  • Wow, another UB in c++? ... – Larry Sep 11 '20 at 15:17
  • 1
    There's a lot of possible UB in C++. We have a (non-exhaustive, and somewhat outdated) list here: [What are all the common undefined behaviours that a C++ programmer should know about?](https://stackoverflow.com/questions/367633/what-are-all-the-common-undefined-behaviours-that-a-c-programmer-should-know-a) – Yksisarvinen Sep 11 '20 at 15:21

1 Answers1

1

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.

cigien
  • 57,834
  • 11
  • 73
  • 112