References and memory

Hi, I have a few questions about references.

Consider the following code:

#include <iostream>
using namespace std;
int main()
{
int x = 10; // line 1
int& y = x; // line 2
cout << &x << endl; // line 3
cout << &y << endl; // line 4
}

When running this program, lines 3 and 4 print out the same memory address. My impression was that the memory allocation in this program, starting from line 1, went like this:

line 1: allocate memory on the stack for x, copy the value 5 into the bucket
line 2: allocate memory on the stack for y, copy the memory address of x into the bucket
line 3: print out the memory location of the bucket for x
line 4: print out the memory location of the bucket for y

Since line 4 prints out what appears to be the memory location of the bucket for x, does this mean that the & operator works differently on reference types (return the memory address contained in y rather than the memory address of the bucket for y), or that y is sharing the same memory location as x, or something else?

Thanks.
The behaviour you describe would be correct if y was an int*. There are a few juicy topics on References floating around the forum right now, if you really want to read more, but prepare for severe headaches.
You can think of references like this, they are just a "label" for the value in memory, no additional memory is used. Instead of referring to a variable by it's memory address 0x0F032010 we can name that address in your case y

In other words, a reference is just a name, another name for a variable or any object for that matter.
Last edited on
In other words, a reference is just a name, another name for a variable or any object for that matter.


Bingo. It's another name for the exact same thing in the exact same piece of memory.

Unless you want to end up in a screaming match, go no further :)

How C++ is to implement references is not specified in the standard, and as such opinions on what a reference "is" vary significantly.
if you declare int& y=x, y will have the same adress as x, and therefore line 3 and 4 print tha same thing, and whaever you do to x, the same is done with y.
Thanks guys.
Topic archived. No new replies allowed.