Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of const reference after casting to non-const

I am somewhat confused about the following piece of code. How can b still reference a but have a different value?

#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;
}
like image 694
danwin Avatar asked Dec 10 '22 12:12

danwin


1 Answers

This behavior is undefined.

You can legally cast const-ness away from a constant reference of a non-constant object; however, casting const-ness from a reference that references a real const leads to undefined behavior.

In this case, it appears that the compiler created a memory location to store 5 in order to provide you with a location to which to make a reference b, while variable a itself is optimized into a constant. Your code illegally modifies the location referenced by b, producing 6, while the line

cout << a << endl;

is optimized into

cout << '5' << endl;

so it still produces a 5.

like image 127
Sergey Kalinichenko Avatar answered Jan 16 '23 06:01

Sergey Kalinichenko