Mental model
A variable is a named piece of storage. What that storage holds decides what an assignment does:
- If it holds the value itself (a number, or every field of a small struct), then
b = acopies the value. Afterwardsaandbare independent: changing one never affects the other. - If it holds a reference (in effect, the address of an object somewhere else), then
b = acopies only the reference. There is still one object, now reachable under two names. Those names are aliases.
The lab draws variables as blocks in the stack lane and objects as blocks in the heap lane. A value copy makes a second block; a reference copy makes a second arrow to the same block.
Mutating vs rebinding
With two aliases p and q for one object, two very different things can happen next:
| Statement | What changes | Visible through p? |
|---|---|---|
q.x = 9 |
the object both names refer to | yes |
q = new Point(0) |
only where q points |
no |
This distinction explains most "why did my list change?" surprises. A method that receives a reference can mutate the caller's object, but assigning a new object to its parameter only changes its own copy of the reference.
What each language does
C#
Structs, enums and the built-in numeric types, bool and char are value types: assignment and
argument passing copy the whole value. Classes, interfaces, delegates, arrays and string are
reference types. The lab's C# rules use a struct PointValue for the first half and a
class PointRef for the second.
Two things blur the line. ref, in and out parameters pass a variable by reference, so a callee
can assign to the caller's variable. And converting a struct to object or an interface boxes
it: the value is copied into a new heap object, so later changes to the original do not reach the
box.
Java
Java has eight primitive types (int, long, double, boolean, …) whose variables hold values.
Every other variable holds a reference. Java passes everything by value, and for an object the
value passed is the reference: a method can mutate your object but cannot make your variable point
somewhere else. Java 25 has no user-defined value types, which is why the lab's Java rules use an
int for the value half.
== on references compares identity. Boxed numbers are objects too: boxing reuses cached Integer
objects only for values from −128 to 127 (JLS §5.1.7), so compare boxed values with equals.
Python
Every Python variable is a name bound to an object, even for numbers. b = a always binds b to the
object a refers to, so a is b is true. What makes ints feel like values is that they are
immutable: no operation can change the object, so sharing it is harmless. b = 9 rebinds b to
another object. Lists, dicts, sets and your own class instances are mutable, and there sharing is
visible.
is tests identity, == tests equality. A classic trap is grid = [[0] * 3] * 3: the outer list
holds three references to one inner list.
C++
Objects are values by default: Point b = a; runs the copy constructor and b is a separate object.
Indirection is always explicit:
- A reference
Point& r = a;is another name for an existing object. It must be bound when declared and can never be re-seated. - A raw pointer
Point* p = &a;holds an address. It can be null, re-pointed and compared. - Smart pointers own heap objects:
std::unique_ptr(one owner, move-only) andstd::shared_ptr(shared ownership with a use count). The lab's C++ rules useshared_ptr, because copying it behaves like copying a reference in the other three languages.
References and raw pointers do not keep their target alive. A reference to a local that has gone out of scope dangles, and using it is undefined behaviour.
Shallow and deep copies
Copying a value that contains references copies the references, not what they point to. That is a shallow copy.
- A C# struct with an array field: copying the struct copies the array reference, so both copies share one array.
- Python's
copy.copy(lst)makes a new list holding the same element objects;copy.deepcopyrecursively copies them too. - Java's
clone()on anArrayListis shallow; so isnew ArrayList<>(other). - In C++, the default copy constructor copies each member; a raw pointer member is copied as an address, which is why classes that own memory define their own copy operations (or use smart pointers and containers that do).
Costs
Copying a value costs time proportional to its size; copying a reference costs O(1) whatever the
object's size. That is why large structs in C# are often passed with in, large C++ objects with
const&, and why reference types are the default for big data in Java and Python. The price of
sharing is aliasing: you have to know who else can see the object.
Common mistakes
- Assuming a method "returns" a change by assigning to its parameter. It changes only its local copy.
- Mutating a list that was passed in when the caller did not expect it.
- Comparing objects with
==in Java, or withisin Python, when equality was meant. - Returning a reference or pointer to a C++ local variable.
- Using a mutable default argument in Python (
def f(items=[])): the same list is shared by every call.
Edge cases
- Strings are reference types in C# and Java but immutable, so they behave like values in practice.
- A C#
readonly structor a C++constobject cannot be mutated through any alias. - CPython caches small ints, so
a is bcan be true even for two separately created5s. Never rely on it.
Worked practice
1. In C#, var a = new PointValue(1); var b = a; b.X = 2; What is a.X?
Answer
PointValueis a struct, sobis a copy; changing it leavesaalone.
2. In Python, xs = [1, 2]; ys = xs; ys.append(3). What is xs, and why? What if the last statement were ys = ys + [3]?
Answer
[1, 2, 3]: ys and xs name the same list and append mutates it. With ys = ys + [3], a new
list is built and bound to ys; xs stays [1, 2].
3. A Java method does list = new ArrayList<>(); list.add(1);. Does the caller's list change?
Answer
No. The method rebinds its own parameter to a new list and adds to that one. The caller's variable still refers to the original list.
Summary
- Assignment copies what the variable holds: a value, or a reference to an object.
- Mutation through an alias is visible through every alias; rebinding a variable is not.
- C# structs and C++ objects are copied by default; Java objects and every Python object are reached through references.
- Shallow copies share inner objects; deep copies do not.
- References and pointers that do not own their target can dangle in C++.