I understand what both "int a = b" and "int* a = &b" mean, but is confused when I just saw "int& a = b".
My guess is both "a" and "b" are integers in this expression, but the address of "b" will be also assigned to be equal to the address of "a". The variable "a" remains to be an integer instead of a pointer.
int a = b is setting a's VALUE to b's VALUE
int* a = &b is setting a's VALUE to the ADDRESS of b
int& a = b is setting a's ADDRESS to b's ADDRESS (a is a reference to b)
binds the integer reference a to b. The address of the variable a is completely unmodified.
It simply means that all uses (references) of a actually use the value assigned to b.
What you are saying is that a IS b (which it isn't, they have different addresses). a just "references" b, meaning that if you change a, (at say, location x0110), then b (at say location x1111) will change too. a will always be at x0110, it won't change.
They do not. You cannot, by standard, take the address of a reference variable.
The declaration int& a = b; allocates four bytes of memory (32-bit machine) and
stores in them the address of b. You cannot, through legitimate, portable means,
determine where in memory those four bytes were allocated.
Of course a reference is handled similarly as a pointer by the compiler. Of course the compiler will allocate sizeof(void*) bytes (not necessarly 4!!) on the stack when one declares a reference. But that's irrelevant, and in fact, a programmer should not care about it.
The two (and only) relevant things about references are, if you have e.g. int& a = b :
- a IS b
- the address of a equals the address of b, i.e. &a == &b
The thing to realize here is that guestgulkan's example was in Debug build (ie: no optimizations). I'd wager an optimized build would have a different result.
yeah, That'ts why I deliberately made sure I said it was in Debug mode.
I'm pretty sure that in the example I gave, the reference could be optmized out in release mode.
What if it's kept in a register the whole time? Then no variable allocation is needed at all, even if the function isn't inlined.
But anyway... sure, there will be instances where a pointer is allocated -- I didn't mean to say otherwise. In fact such instances are quite common.
My point is that you shouldn't think of references this way. IMO, the best way to conceptually look at it is that the reference is the var it refers to.