Constant reference behavior after casting is not constant

I am a little confused in the following code snippet. How does b refer to a but have a different meaning?

#include <iostream>
using namespace std;
int main()
{
    const int a = 5;
    const int &b = a;
    ++(int&)b;
    cout << a << endl;//returns 5
    cout << b << endl;//returns 6
    cout << "mem a:" << &a << endl; //returns 0x61ff18
    cout << "mem b:" << &b << endl; //returns 0x61ff18
    return 0;
}
+4
source share
2 answers

This behavior is undefined.

You can legally distinguish const-ness from a permanent reference to a mutable object; however, the strict constant from the link, which refers to the real one const, leads to undefined behavior.

, 5, b, a , , b, 6,

cout << a << endl;

cout << '5' << endl;

5.

+11

C- const_cast. const_cast, -, , , undefined. , , .


const_cast, :

#include <iostream>

int main()
{
    int a = 5; // <--- non-constant
    const int &b = a;
    ++const_cast<int&>(b);
    std::cout << a << '\n'; // 6
    std::cout << b << '\n'; // 6
    std::cout << "mem a:" << &a << '\n';
    std::cout << "mem b:" << &b << '\n';
}
+2

Source: https://habr.com/ru/post/1672095/


All Articles