I am learning about pointers and references, and my question refers to this explanation, in particular the following section:
This suggests that the declaration int& ri = i
creates a new memory cell, which has a value of &i
and exists in unknown memory location.
To test this theory, I wrote a simple case, the result which is seen below:
I am perplexed by the fact that r
and i
have the same memory address, which seems to contradict the readings. The result suggests that int& ri = i
loosely means "create an alias for memory cell i
and call it r
" such that both refer to exactly the same cell.
Is the document correct, or have I missed something?
Regardless of how a reference is implemented, a reference has the same memory address as the item it references. A reference does not have an address at all. References are not objects, don't have memory or a size and you cannot std::memcpy them.
A reference variable is an alias, that is, another name for an already existing variable. Once a reference is initialized with a variable, either the variable name or the reference name may be used to refer to the variable.
Reference Type variables are stored in a different area of memory called the heap. This means that when a reference type variable is no longer used, it can be marked for garbage collection. Examples of reference types are Classes, Objects, Arrays, Indexers, Interfaces etc.
A reference is not an object, and unlike an object, it is not guaranteed to occupy some contiguous bytes of memory. The standard leaves it unspecified whether a reference requires any storage at all.
Since r
is a reference to i
, all operations on r
are transformed by the compiler into operations on i
. So doing &r
, gives you the memory address i
is in.
(Note that unlike pointers, references have the property of not being 're-referenced' after declared - they always reference the same thing - so there is no way to write operations that operate 'on the reference', not 'on what is referenced')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With