In my last post I went over my considerations around Conjure using a manual memory management model. This meant developers freed everything by hand with a few safety features added to avoid common pitfalls.

This post looks at extending the compiler to support freeing memory for you through an RAII style mechanic, similar to C++. When sharing my memory considerations with other (game) devs who had expressed an interest in using Conjure, this approach was quite popular. I have to imagine this is because these developers are already using C++, so this pattern is very natural to them.

#A running example

It’s going to be a lot easier if we have an example we can point to. Here you can see a scenario where we have a Player that has a name and the Weapon they’re holding, a Weapon points back at its wielder, an Inventory keeps a list of item names, and a World holds all the active players.

struct Player {
  name    string
  health  i32
  weapon  ?*Weapon   // owned: freed with the player when present
}

struct Weapon {
  damage  i32
  wielder ?&Player   // borrowed: never freed
}

struct Inventory {
  items []string     // owned: the strings and the buffer
}

struct World {
  players []&Player  // owned buffer, borrowed elements
}

func main() {
  var hero = alloc(Player{
    name = "Hero",
    health = 100,
    weapon = null,
  })!

  var sword = alloc(Weapon{
    damage = 50,
    wielder = hero,  // *Player narrows to &Player
  })!
  hero.weapon = sword

  var inv = Inventory{ items = []string{} }
  inv.items.append("potion")
  inv.items.append("rope")

  var world = World{ players = []&Player{} }
  world.players.append(hero)

  // ...and everything here cleans up on its own at scope exit.
}
The trailing bang

The alloc() intrinsic in these examples returns ?*T by default, with null accounting for “out of memory” errors. The trailing ! basically asserts the value is not null, otherwise the program will panic at runtime rather than continue on with undefined behavior.

#Auto-free at scope exit

The idea is simple: the compiler tracks which bindings hold heap-owned data and drops a free() in at every scope exit. You never call it yourself in normal code, the same way you’d lean on RAII in C++. Types that need custom teardown, like closing a file handle or notifying observers, get an overload free hook to run their own logic1.

For types without an explicit overload free, free functions are generated for you. The compiler walks the type and emits the right teardown for each field: nested structs free themselves, dynamic arrays release each element and then their buffer, and heap-owned strings free their data. Deeply nested structures clean up correctly without you writing a single line of recursive cleanup.

#Owns by default, no visible moves

The model rests on two properties. Everything owns by default, so any pointer-typed field or local holding owned data gets freed at scope exit with nothing to opt into. And you never see moves: assigning, passing, returning, or storing a binding doesn’t invalidate the source. You can write var alias = sword and keep using both sword and alias afterward, mutate either, pass either around, exactly like you would in C# or Go.

That second property is the inverse of move semantics, where each of those operations would mark the source Moved and lock you out of it. Under the hood the compiler is still doing the bookkeeping to make sure exactly one binding frees each allocation. It just never makes that your problem.

#Owning vs borrowing

Owns-by-default is right for the common case of a parent owning its children, but it can’t be the whole story. Back-pointers, observer lists, and pool views all reference memory they don’t own. That’s what the &T sigil is for: it means borrowed, and the compiler won’t free through it.

That’s the ?&Player on Weapon.wielder back in the example. The weapon refers to its wielder but doesn’t own them, so the compiler leaves that field alone when it frees the weapon. The same reading carries through containers, which is why World.players is a []&Player: the world owns the buffer but not the players sitting inside it, and a Map[K, &V] would free its storage but not the references it holds2.

Function signatures use the sigil too, which makes it the ownership contract:

  • func equip(w *Weapon): takes ownership; the caller’s free responsibility transfers in.
  • func inspect(w &Weapon): borrows; the caller still owns.
  • func makeSword() *Weapon: hands ownership back to the caller.
  • func firstWeapon(p &Player) &Weapon: hands back a borrow tied to p’s lifetime.

Other native container types, like slices [:]T3, follow the same rule, since a slice is just a borrowed view into someone else’s buffer.

The catch is that borrow validity isn’t checked at compile time. If the owner frees the underlying allocation while a &T field or slice still points at it, you’re left with a dangling reference and undefined behavior. It’s the same gotcha that already applies to &T parameters, just extended to fields and containers. Future explorations will try to help catch and resolve these issues.

#Tracking ownership without moves

The no-visible-moves trick is a flow-sensitive pass inside each function. For every allocation, the compiler tracks the set of bindings that currently alias it. The moment one of them escapes to an owning slot outside the function, whether that’s a *T field, a []*T append, or a *T argument or return, the whole set loses its free responsibility and no scope-exit free is emitted.

var sword = alloc(Weapon{...})!   // this scope owns the allocation
var alias = sword                // both names point at it
hero.weapon = sword              // it escapes; the scope stops owning it
// scope exit: neither sword nor alias frees it. hero owns it now.

The aliases stay readable and writable after the handoff. The allocation is still alive, it’s just no longer this scope’s job to release it4.

This extends to any type that transitively holds heap data, not just a bare *T. The compiler sorts every type into plain-old-data (an i32, a Vec3, a struct of values) that copies freely, or heap-bearing (anything containing a *T, string, []T, or Map) that joins the alias graph on assignment. So var bar = foo on an Inventory { items []string } doesn’t blindly bitwise-copy into a double-free; the two share an alias set and ownership transfers on escape like anything else. The category falls out of the type’s fields, so there’s nothing to annotate5.

#When you still reach for @nofree

Alias tracking handles the ordinary handoffs, so @nofree shrinks to a few genuine escape hatches: FFI returns where C owns the memory, rawptr casts where you’ve deliberately bypassed the type system6, and hot paths where you want to drive free() yourself (usually because the allocation is arena-backed). Everyday alloc()-then-store code never needs it.

#Standard library smart pointers

Because this is mechanically close to C++‘s RAII, the smart-pointer family maps straight onto stdlib types with no language changes. Each is a thin wrapper around *T with a hand-written overload free:

Conjure typeC++ analogSemantics
*Tstd::unique_ptrSingle owner, frees the value on scope exit
Rc[T]std::shared_ptrRefcounted shared ownership, non-atomic (thread-local)
Arc[T]std::shared_ptrRefcounted shared ownership, atomic (cross-thread)
Weak[T]std::weak_ptrNon-owning observer to an Rc/Arc, upgrades fallibly

You opt into shared ownership by reaching for the type, not by the language forcing a model on everyone. It’s the same move Swift, C++, and modern Rust make, and it keeps the core language small.

#overload free and explicit free()

An overload free hook runs as part of a type’s teardown7, so you can do cleanup that still needs the fields intact. If the generated walk is wrong for a type, the hook can do everything itself, with the fields declared as &T or rawptr so the compiler keeps its hands off.

Explicit free(x) is still there for early cleanup, and it consumes the whole alias set the binding belongs to. After free(sword), using an earlier var alias = sword is a compile error. That’s the only place moves become visible, and it’s narrow, triggered by the free() call itself and nothing else8.

It’s also worth noting that auto-free only works because the compiler can look at a type and know exactly what to release. A C-style untagged union (which Conjure supports for C interop) breaks that. It holds one of several members but never records which one is live, so the compiler can’t tell whether the active member owns memory or which cleanup to run. Guessing wrong means either a leak or freeing a pointer that was never really there. This means Conjure would need to treat a raw union as an explicitly manual construct and wouldn’t be able to automatically free it for you.

#Where that leaves auto-free

Let’s look at the scoreboard, which for us is a pros and cons list.

  • Owns-by-default matches tree-shaped ownership, so simple code needs no annotations.
  • *T vs &T carries ownership in the type; back-pointers and pool views just read as &T.
  • The same sigil doubles as the function ownership contract, no @owned/@borrowed keywords.
  • No visible moves; bindings stay usable after being shared, like in C# or Go.
  • Cleanup is centralized in overload free and runs at predictable scope-exit points.
  • Still zero-cost at runtime, with stable pointers that don’t move under the debugger.
  • Borrowed &T fields and slices aren’t validity-checked; a dangling borrow is UB, not a panic.
  • Alias tracking is real compiler complexity, including hidden flags for branch-divergent escapes.
  • Container ownership is uniform: []*T or []&T, but not a mix in one array.
  • Cyclic cleanup still needs care; indirect cycles can stack-overflow.
  • @nofree survives for FFI, rawptr, and hot paths, so it’s not quite annotation-free.

Auto-free is nice since it holds the zero-runtime-cost aspect with no (implicit) refcounts or generation bumps riding along pointers and hurting cache locality, while still taking teardown off my hands.

Aside from a handful of cases, the &T sigil seems sound: a back-pointer or pool view can say it doesn’t own its target right there in the type; a vocabulary that an ECS or arena-heavy codebase wants. It plays nicely with arenas too, since marking the arena-backed pointers as borrowed stops the compiler from freeing through them.

The one thing it doesn’t do is catch a dangling &T the moment you touch it. That’s still undefined behavior rather than a clean crash.