(C ++ memory management) If we have int x = 1234, and int & y = x ... then what is the address y on the stack?

We are learning on our medium-term facility on Tuesday.

Our professor has posted some training materials on the Internet, including the following:

"In addition, you should be able to draw a memory diagram with some code, for example:

void foo( int &x ) { x = 1000; } void bar( int *x ) { *x = 1000; } void foobar( int x ) { x = 1000; } int main() { int x = 1234; int &y = x; int *z = &x; int array_1[5]; int *array_2[5]; array_1[0] = 10; array_2[0] = (int*)10; array_2[1] = &y; array_2[2] = &x; foo( x ); foo( y ); foo( *z ); bar( &x ); bar( &y ); bar( z ); foobar( x ); foobar( y ); foobar( *z ); return 0; } 

We try to go through it one step at a time to find out what is allocated on the stack, what is allocated on the heap, and what is the value of each thing.

We do not understand: & y contains the address x, but & y = & x ... so what is the address y? For example, does the stack need to stack y

+4
source share
4 answers

In short, there is no spoon y . That way nothing will be allocated on the stack for y . This is because y is a link in your case.

A link is just an alias and has no address. In other words, this is the same as x , but in different ways. This is how you should think of links as a C ++ programmer. In fact, the compiler can use the address of the object to implement the link (i.e., when passing by reference). And even in this case, it can only be stored in a register, therefore it does not have a memory address. But these are implementation details that you should not be aware of. I recommend that you familiarize yourself with this C ++ References FAQ .

+8
source

y is neither an object nor a function, so it has no address. This is a reference to the variable x , which means that whenever you use y , you use x . Note that this does not require y contain a pointer to x at all.

In the main , y function, it probably doesn't exist at all in the generated executable; the compiler can trivially replace all uses of y , as if they were using x .

In your bar function (again, assuming that it really exists in the generated executable file and is not fully inlined), x , which is the link, must exist somewhere, because it must refer to an object outside the scope of the function. Such links are usually implemented as pointers, but developers are free to use links, but they are best suited.

+3
source

Think of links as "just a different name." In other words, β€œy” is just another name for β€œx” and therefore has no address.

+1
source

Relatively int & y = x; If you look at the assembly (compiled with -S), you will see that in many cases the address x is pushed onto the local stack .... therefore, you can read this stack address as the address y.

0
source

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


All Articles