Link - const pointer

I read in many places the links:

Link is like const pointer

Link always refers to an object

After initialization, the link cannot be restored.

I want to clarify the last point. What does it mean?

I tried this code:

#include <iostream> int main() { int x = 5; int y = 8; int &rx = x; std::cout<<rx<<"\n"; rx = y; //Changing the reference rx to become alias of y std::cout<<rx<<"\n"; } 

Exit

 5 8 

Then what does it mean: “Links cannot be reinstalled”?

+6
source share
3 answers

This line:

 rx = y; 

Doesn't make rx a y point. This means that the value of x (via the link) becomes the value of y. Cm:

 #include <iostream> int main() { int x = 5; int y = 8; int &rx = x; std::cout << rx <<"\n"; // Updating the variable referenced by rx (x) to equal y rx = y; std::cout << rx <<"\n"; std::cout << x << "\n"; std::cout << y << "\n"; } 

Thus, it is not possible to change what rx means after its initial assignment, but you can change the value of the object reference.

The link therefore looks like a constant pointer (where the address of the pointer is a constant, not a value at that address) for the purposes of this example. However, there are important differences, one good example (as Damon noted) is that you can assign temporary links to local constant links, and the compiler will extend their lifetime to preserve it throughout the link life cycle.

Significant additional information about the differences between links and constant pointers can be found in the responses to this SO message .

+13
source

You changed the value of x to the value of y :-)

+6
source

int &rx = x; makes rx alias of x .

Then rx = y implies x = y

After creating an alias, any use of it ( rx ) will be equivalent to using x. You cannot undo this (drag rx ) to make rx alias, for example, "y".

+6
source

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


All Articles