I understood, a temporary const int object whos value is a will be created and b will be initialized with it,
You are wrong. Neither temporary object is created in this code snippet
int a = 1; const int &b = a;
Moreover it is even unspecified in the C++ Standard whether a memory allocated for the reference b.
You should consider the reference b as an alias for the variable a.
As the reference refers the object a as a constant object you may not use the reference to change the object a. Nevertheless the object a is declared as a non-constant object. So you may change its value like
a = 2;
but you may not change it using the reference like
b = 2;
You could use the reference to change the value of the object a if the reference was declared like
int &b = a;
In this case the result of these two statements
a = 2;
and
b = 2;
will be equivalent.
As for this code snippet
int a = 1; const int x = a; const int &b = x; a = 2; std::cout<<b;
then the constant x is assigned with a copy of the value of the variable a. x and a are two different objects that occupy different extents of memory.
The reference b is declared as a reference to the object x.
const int &b = x;
So changing the object a does not influence on the value of the constant x. The constant x may not be changed neither directly nor by using the reference b.
const intobject whos value isawill be created andbwill be initialized with it, so, it is as if I wrote this code Is incorrect. No temporary value is involved.brefers directly toa.bCAN refer to a temporary (and will extend the lifespan of this temporary) but that is not what is happening here.std::cout<<b;withstd::cout<<b<<"\n"; std::cout<<((a!=b)?a:b);show what's happening?