Link and const mess in C ++

I knew that a link is just another variable name, 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 riis an alias of what? [value 24 in memory]

+4
source share
1 answer

You cannot directly link a link to an object with another type.

For const int &ri = i;, you ifirst need to convert to int, then create a temporary one intand then attach it to it ri; it has nothing to do with the original object i.

BTW: the lifetime of a temporary is extended to fit the lifetime of a link here.

BTW2: lvalue-reference const rvalue-reference.

+3

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


All Articles