Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a reference create a new location in memory, or an alias for an existing cell? [duplicate]

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:

enter image description here

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?

like image 634
jII Avatar asked Jun 13 '13 05:06

jII


People also ask

Does a reference have a memory address?

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.

What is alias in reference?

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.

Do reference variables store memory locations?

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.

Does reference occupy memory?

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.


1 Answers

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')

like image 86
Patashu Avatar answered Oct 23 '22 09:10

Patashu