Link Explanation in C ++

So, I'm trying to learn C ++, and I came across something that puzzles me a bit. I have a code,

int x = 0; int &y = x; cout << &x<< " " << x << " " << &y << " " <<y<< endl; 

This compiles and it turns out:

 0 003AFA08 0 003AFA08 

Which is hard for me to understand why converting x, int, to & y, a link, does not lead to an error. At first I thought it was some kind of translation,

 int &y = &x; 

leads to an error.

Can someone explain why this works this way? Thanks in advance.

+6
source share
4 answers

int& not an address. This is a link.

int& y = x; declares y as a reference to x . This actually means that y becomes a different name for x . Each time you use y , it is as if you said x .

Pointers (not links) are used to store addresses. int& y = &x; invalid because &x is the address of x (it a int* ). y is a reference to int , not a reference to int* .

+11
source

This is not a conversion. When you have a variable type T & , where T is a random type, you basically say: "I declare a name that is an alias for another name or possibly an anonymous value." This is more like a typedef than a pointer.

Links are often implemented as addresses, but this is not a good model to think about what they are.

In your example, what are you puzzled:

 int * const &y = &x; 

will work fine. Then y becomes an alias for the temporary result of accepting the address x . Please note that this is a link to a pointer. It must be a reference to a constant pointer, because it is a reference to a temporary value.

+5
source

&y is not just an address, it is a link. It means that

 int &y = x; 

makes clone x name y .

+2
source

Your problem is that &y is not just an address, but a link. This means that it behaves like a copy of x . It does not convert and actually becomes a different name for x .

+1
source

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


All Articles