Memory Model
Overview
Cera uses a hybrid memory model: types are value types (stack-allocated by default), while GC-managed heap objects are accessed through typed references.
GC References
Append ? or ! to a type to create a heap-allocated GC reference:
T?— nullable reference (may benull)T!— non-null reference (compiler-enforced)
type Node{ int value; Node? next;}
Node! n = new Node();n.value = 10;n.next = null;The garbage collector automatically frees unreachable objects.
Safe Navigation and Null Coalescing
string? name = person?.Name;string display = name ?? "unknown";
// Null coalescing assignmentname ??= "default";Value Types (Stack)
Plain types without ? or ! are value types — copied on assignment:
Point a = Point(1.0, 2.0);Point b = a; // b is a copyb.x = 99.0;Console.WriteLine($"{a.x}"); // still 1.0Reference Parameters
Pass a value by reference using ref, or use in for immutable by-reference (immut ref):
void Increment(ref int n){ n = n + 1;}
int x = 5;Increment(ref x);Console.WriteLine($"{x}"); // 6
// 'in' passes by reference without allowing modificationint ReadOnly(in int n) { return n; }Raw Pointers
For low-level interop, Cera supports unmanaged pointers inside unsafe blocks:
T*— nullable raw pointerT&— non-null raw pointer
Use new* to allocate and delete* to free raw memory:
unsafe{ int* p = new* int(); // allocate a raw int pointer *p = 42; int val = *p; delete* p; // manual free
int x = 10; int& q = &x; // non-null pointer to stack variable *q = 20;}Raw pointers are not tracked by the GC. You are responsible for calling delete* to avoid memory leaks.
Move and Copy Semantics
Use copy for explicit value duplication and move for ownership transfer:
type Data { int a; int b; }
Data d1;d1.a = 10;d1.b = 20;
Data d2 = copy d1; // d2 is a copyData d3 = move d1; // d1 is invalidatedCopy and Move Operators
Control type copying and moving with =(copy) / =(move) and : default / : delete:
type Resource{ void =(copy) : default; // auto-generated copy void =(move) : delete; // disallow move}GC Pools
The garbage collector organizes heap objects into three pools:
| Pool | Description |
|---|---|
| Spawn | Nursery / young generation. New objects are allocated here. Collected frequently. |
| Arena | Old generation. Objects that survive multiple Spawn collections are promoted here. |
| Permanent | Long-lived or static objects. Rarely collected. |
Objects are automatically promoted from Spawn to Arena after surviving enough minor collections. You do not need to manage pool placement manually.
Stack vs. Heap Summary
| Syntax | Allocation | Lifetime | GC Tracked |
|---|---|---|---|
T | Stack | Scope-bounded | No |
T? | GC heap | Until unreachable | Yes |
T! | GC heap | Until unreachable | Yes |
T* | Manual | Explicit free | No |