Memory Lab · simulation 1 of 5
Values and references
Assignment copies either the data or only a reference to it. Watch a copy stay independent while an alias sees every change.
The full explanation is in the lesson Values, references and pointers.
What to watch for
- After b = a, does b get its own block, or a second arrow to the same block?
- q.x = … changes the object both p and q point to; q = new … only moves q’s arrow.
- Switch the language rules: Python shows names bound to objects even for ints.
In each language
- C#
- Structs (and int, double, …) are copied on assignment; class variables hold references.
- Python
- Every name refers to an object. Immutable objects (int, str, tuple) make sharing harmless.
- Java
- Primitives hold values; every other variable holds a reference. Java 25 has no user-defined value types.
- C++
- Objects are values by default; pointers, references and smart pointers are explicit indirection.
The programs
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