Learning path

Full curriculum

Full curriculum

Unit content

References, object identity and heap-allocated values

A variable does not always contain an entire value directly. In many programming languages, a variable can instead hold a reference to a value stored elsewhere.

Two variables can therefore refer to the same underlying object:

left  ─┐
       ├──→ object A
right ─┘

This is aliasing. Changing a mutable object through one reference can then be observed through another reference to the same object.

Identity asks whether two references designate the same object. Equality asks whether two values should be considered equivalent according to some rule. Two separately created objects can be equal without having the same identity.

Values whose lifetime or size cannot be tied conveniently to one function call are commonly created in dynamically managed storage, often called the heap. A heap allocation remains available while the program's runtime rules say that it is still alive; the exact mechanism depends on the language.

References can form graphs. If object $A$ refers to $B$, and $B$ refers to $C$, following references from $A$ can reach both $B$ and $C$. Cycles are also possible: two objects may refer to each other.

These ideas are independent of any one memory-management strategy. Some languages require explicit deallocation, some use ownership rules, and others use garbage collection. All of them need a model of which objects exist, how references connect them, and how long those objects remain valid.