Search code examples
c++referenceconstantstemporary

reference and const confusion in C++


I knew that reference is just another name of a variable, they do not exist as a separate object in memory but what is happening here

double i = 24.7;
const int &ri = i;  //notice int here
std::cout << i << std::endl; //prints 24.7
i = 44.4;
std::cout << ri << std::endl; // prints 24
std::cout << i << std::endl; //prints 44.4

My question is ri is alias of what ? [value 24 in somewhere memory]


Solution

  • You can't bind reference to object with different type directly.

    For const int &ri = i;, i needs to be converted to int at first, then a temporary int is created and then bound to ri, it has nothing to do with the original object i.

    BTW: The lifetime of the temporary is extended to match the lifetime of the reference here.

    BTW2: Temporary can only be bound to lvalue-reference to const or rvalue-reference.