M02 · Memory Model

Values, References and Pointers: What an Assignment Copies

Every assignment copies something. Sometimes it copies the data itself, and the two variables go their separate ways. Sometimes it copies only a reference, and both names lead to the same object, so a change made through one is visible through the other. Knowing which happens is the first step to reasoning about memory.

~30 minBeginnerC# · Python · Java · C++
Curriculum: M02 Memory Model · 5 of 5 lessons available

You will be able to

  • Predict whether an assignment or an argument copies a value or a reference in C#, Python, Java and C++.
  • Tell mutating an object apart from rebinding a variable, and explain why only the first is visible through an alias.
  • Explain shallow and deep copies, and spot a value that secretly contains a reference.
  • Describe C++ references, raw pointers and smart pointers, and when each can dangle.

Helpful before this lesson

  • M01 Algorithmic Thinking — Turn a vague task into precise inputs, outputs and constraints, then argue that a solution is correct.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

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 = a copies the value. Afterwards a and b are independent: changing one never affects the other.
  • If it holds a reference (in effect, the address of an object somewhere else), then b = a copies 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) and std::shared_ptr (shared ownership with a use count). The lab's C++ rules use shared_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.deepcopy recursively copies them too.
  • Java's clone() on an ArrayList is shallow; so is new 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 with is in 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 struct or a C++ const object cannot be mutated through any alias.
  • CPython caches small ints, so a is b can be true even for two separately created 5s. 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
  1. PointValue is a struct, so b is a copy; changing it leaves a alone.

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++.

Full implementation

The same program in four languages, checking each claim the lab makes as it runs (copies are independent, an alias sees a mutation, rebinding leaves the original alone), plus argument passing; run by xUnit, unittest, a java -ea harness and an assert-based C++ test under ASan/UBSan.

namespace Bekadan.Dsa.Examples.Memory;
 
/// <summary>A struct is a value type: assigning it copies every field.</summary>
public struct PointValue(int x)
{
    public int X = x;
}
 
/// <summary>A class is a reference type: a variable holds a reference to one shared object.</summary>
public sealed class PointRef(int x)
{
    public int X { get; set; } = x;
}
 
/// <summary>The Memory Lab's values-and-references program. Every claim it makes is checked.</summary>
public static class ValuesAndReferences
{
    /// <summary>Returns (a.X, b.X, p.X, q.X) after the program has run.</summary>
    public static (int A, int B, int P, int Q) Run(int start, int change)
    {
        var a = new PointValue(start);
        var b = a;                     // copies the whole struct
        b.X = change;
        Check(a.X == start && b.X == change, "a struct copy is independent of the original");
 
        var p = new PointRef(start);   // the object is on the heap; p holds a reference
        var q = p;                     // copies the reference: one object, two names
        Check(ReferenceEquals(p, q), "p and q refer to the same object");
        q.X = change;
        Check(p.X == change, "a change made through q is visible through p");
        q = new PointRef(0);
        Check(p.X == change && q.X == 0 && !ReferenceEquals(p, q), "rebinding q leaves p and its object alone");
        return (a.X, b.X, p.X, q.X);
    }
 
    /// <summary>Passing works the same way: a struct argument is a copy; a class argument is a copy of the reference.</summary>
    public static void Passing()
    {
        static void Bump(PointValue v, PointRef r)
        {
            v.X++;
            r.X++;
        }
        var value = new PointValue(1);
        var reference = new PointRef(1);
        Bump(value, reference);
        Check(value.X == 1 && reference.X == 2, "the callee changed its struct copy, but the shared object");
    }
 
    private static void Check(bool condition, string claim)
    {
        if (!condition) throw new InvalidOperationException($"Claim failed: {claim}");
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Memory/ValuesAndReferences.cs

"""Values vs references in Python: every variable is a name that refers to an object."""
 
from dataclasses import dataclass
 
 
@dataclass
class Point:
    x: int
 
 
def _check(condition: bool, claim: str) -> None:
    if not condition:
        raise AssertionError(f"Claim failed: {claim}")
 
 
def run(start: int, change: int) -> tuple[int, int, int, int]:
    """The Memory Lab's values-and-references program. Returns (a, b, p.x, q.x)."""
    a = start
    b = a  # copies the reference: a and b name the same int object
    _check(a is b, "after b = a, both names refer to one object")
    b = change  # rebinds b; ints are immutable, so no object changes
    _check(a == start and b == change, "rebinding b does not affect a")
 
    p = Point(start)
    q = p  # one object, two names
    _check(q is p, "p and q refer to the same object")
    q.x = change
    _check(p.x == change, "a change made through q is visible through p")
    q = Point(0)
    _check(p.x == change and q.x == 0 and p is not q, "rebinding q leaves p and its object alone")
    return a, b, p.x, q.x
 
 
def passing() -> None:
    """Arguments are passed the same way: the callee gets another name for the same object."""
 
    def bump(n: int, point: Point) -> None:
        n += 1  # rebinds the local name n only
        point.x += 1  # mutates the shared object
 
    n = 1
    point = Point(1)
    bump(n, point)
    _check(n == 1 and point.x == 2, "rebinding inside the callee is local; mutation is shared")

Tested on CPython 3.14.0 · examples/python/dsa_examples/memory_values_references.py

package dev.bekadan.dsa.memory;
 
/**
 * Values vs references in Java: a primitive variable holds the value itself; any other
 * variable holds a reference to an object. (Java 25 has no user-defined value types.)
 */
public final class ValuesAndReferences {
    private ValuesAndReferences() {
    }
 
    /** An ordinary class: always reached through references. */
    public static final class Point {
        public int x;
 
        public Point(int x) {
            this.x = x;
        }
    }
 
    /** The Memory Lab's values-and-references program. Returns {a, b, p.x, q.x}. */
    public static int[] run(int start, int change) {
        int a = start;
        int b = a;                     // copies the number itself
        b = change;
        check(a == start && b == change, "a primitive copy is independent of the original");
 
        Point p = new Point(start);    // the object is on the heap; p holds a reference
        Point q = p;                   // copies the reference: one object, two names
        check(q == p, "p and q refer to the same object");
        q.x = change;
        check(p.x == change, "a change made through q is visible through p");
        q = new Point(0);
        check(p.x == change && q.x == 0 && p != q, "rebinding q leaves p and its object alone");
        return new int[] {a, b, p.x, q.x};
    }
 
    /** Java passes everything by value; for objects, the value passed is the reference. */
    public static void passing() {
        Point point = new Point(1);
        int n = 1;
        bump(n, point);
        check(n == 1 && point.x == 2, "the callee changed its own int, but the shared object");
    }
 
    private static void bump(int n, Point point) {
        n++;
        point.x++;
        check(n == 2, "the callee's n is its own copy");
    }
 
    /** Boxed integers are objects: compare them with equals. */
    public static void boxing() {
        Integer small1 = 100;
        Integer small2 = 100;
        check(small1 == small2, "boxing reuses cached Integer objects for -128..127 (JLS 5.1.7)");
        Integer big1 = 1000;
        Integer big2 = 1000;
        check(big1.equals(big2), "equals compares values; == on big boxed values compares references");
    }
 
    private static void check(boolean condition, String claim) {
        if (!condition) {
            throw new AssertionError("Claim failed: " + claim);
        }
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/memory/ValuesAndReferences.java

#pragma once
 
#include <cassert>
#include <memory>
#include <tuple>
 
namespace bekadan::dsa::memory {
 
// In C++ every object is a value unless you ask for indirection: a copy copies the
// members. Pointers (raw or smart) and references are the explicit ways to share.
struct Point {
    int x;
};
 
// The Memory Lab's values-and-references program. Returns {a.x, b.x, p->x, q->x};
// every claim it makes is checked with assert.
inline std::tuple<int, int, int, int> values_and_references(int start, int change) {
    Point a{start};
    Point b = a;                                  // copies every member
    b.x = change;
    assert(a.x == start && b.x == change);        // the copy is independent
 
    auto p = std::make_shared<Point>(Point{start});
    auto q = p;                                   // copies the pointer: one Point, use_count() == 2
    assert(p.get() == q.get() && p.use_count() == 2);
    q->x = change;
    assert(p->x == change);                       // visible through every pointer to it
    q = std::make_shared<Point>(Point{0});
    assert(p->x == change && q->x == 0 && p != q && p.use_count() == 1);
    return {a.x, b.x, p->x, q->x};
}
 
// A reference is another name for an existing object and cannot be re-seated;
// a pointer holds an address and can be pointed elsewhere.
inline void references_and_pointers() {
    Point a{1};
    Point& alias = a;
    alias.x = 2;
    assert(a.x == 2);
    Point other{7};
    Point* ptr = &a;
    ptr = &other;
    assert(ptr->x == 7 && a.x == 2);
}
 
}  // namespace bekadan::dsa::memory

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/memory/values_references.hpp

References