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;
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With