Generational Handles
A pointer says where an object is. In a game that is the wrong question, because objects die and their memory is reused while other objects still refer to them: the missile tracking an enemy, the UI marker above a quest giver, the sound attached to a door. A handle says which object is meant, and can answer "is it still alive?".
The standard design, used by most modern engines and libraries (entity IDs in EnTT and flecs, resource IDs such as sokol_gfx's sg_buffer and sg_image), is a generational index: a small struct holding a slot index and a generation counter.
- The pool keeps a generation number per slot.
- When a slot is freed, its generation is incremented.
- A handle is valid only if its generation equals the slot's current generation.
So a handle created before the slot was reused carries an old generation and is rejected, instead of silently referring to the new occupant.
A handle pool
The handle is packed into 32 bits (20 bits of index, 12 bits of generation) so it is as cheap to store and compare as an int:
#include <cstdint>
#include <cstdio>
#include <optional>
#include <string>
#include <vector>
struct Handle {
std::uint32_t bits = 0; // 0 = null handle
static constexpr std::uint32_t kIndexBits = 20, kGenMask = (1u << 12) - 1;
std::uint32_t index() const { return bits & ((1u << kIndexBits) - 1); }
std::uint32_t gen() const { return bits >> kIndexBits; }
static Handle make(std::uint32_t index, std::uint32_t gen) { return {(gen << kIndexBits) | index}; }
bool operator==(const Handle&) const = default;
};
template <class T>
class HandlePool {
struct Slot { std::optional<T> value; std::uint32_t gen = 1; }; // gen starts at 1: bits never 0
std::vector<Slot> slots_;
std::vector<std::uint32_t> freeList_;
public:
Handle create(T value) {
std::uint32_t i;
if (!freeList_.empty()) { i = freeList_.back(); freeList_.pop_back(); }
else { i = std::uint32_t(slots_.size()); slots_.emplace_back(); }
slots_[i].value = std::move(value);
return Handle::make(i, slots_[i].gen);
}
T* get(Handle h) { // nullptr if dead or stale
if (h.index() >= slots_.size()) return nullptr;
Slot& s = slots_[h.index()];
return (s.value && s.gen == h.gen()) ? &*s.value : nullptr;
}
bool destroy(Handle h) {
if (!get(h)) return false;
Slot& s = slots_[h.index()];
s.value.reset();
s.gen = (s.gen + 1) & Handle::kGenMask;
if (s.gen == 0) s.gen = 1; // skip 0 so handles are never null
freeList_.push_back(h.index());
return true;
}
};
struct Enemy { std::string name; int hp; };
void report(HandlePool<Enemy>& pool, const char* who, Handle h) {
Enemy* e = pool.get(h);
std::printf("%-14s handle=0x%08x (index %u, gen %u) -> %s\n", who, h.bits, h.index(), h.gen(),
e ? e->name.c_str() : "INVALID");
}
int main() {
HandlePool<Enemy> enemies;
Handle goblin = enemies.create({"goblin", 30});
Handle orc = enemies.create({"orc", 80});
Handle missileTarget = goblin; // a missile locks on
report(enemies, "missile target", missileTarget);
enemies.destroy(goblin); // goblin dies
Handle troll = enemies.create({"troll", 200}); // reuses slot 0
report(enemies, "troll", troll);
report(enemies, "missile target", missileTarget); // stale: same index, old generation
report(enemies, "orc", orc);
std::printf("destroy goblin again: %s\n", enemies.destroy(goblin) ? "destroyed" : "ignored (stale)");
std::printf("sizeof(Handle) = %zu\n", sizeof(Handle));
}missile target handle=0x00100000 (index 0, gen 1) -> goblin
troll handle=0x00200000 (index 0, gen 2) -> troll
missile target handle=0x00100000 (index 0, gen 1) -> INVALID
orc handle=0x00100001 (index 1, gen 1) -> orc
destroy goblin again: ignored (stale)
sizeof(Handle) = 4
With a raw pointer, the missile would now be chasing the troll. With the handle, get returns nullptr and the missile can pick a new target or fly straight.
Generation wraparound. With 12 generation bits a slot can be reused 4095 times before an old handle could match again by accident. That is plenty for most uses, but a slot that is recycled every frame for a long session wraps around. Options: use more bits (32-bit index + 32-bit generation in a uint64_t), or retire a slot when its generation reaches the maximum instead of wrapping.
Handles let you move data
Because nobody holds a pointer, the pool is free to move objects. That allows the most cache-friendly layout of all: keep live objects densely packed in an array with no holes, and translate handles through an indirection table. Removing an object moves the last element into the hole (swap-and-pop) and fixes one table entry:
#include <cstdint>
#include <cstdio>
#include <vector>
struct Handle { std::uint32_t index, gen; };
struct Particle { float x; int id; };
class DensePool {
struct Entry { std::uint32_t dense; std::uint32_t gen; bool alive; };
std::vector<Entry> sparse_; // handle.index -> position in dense_
std::vector<std::uint32_t> denseToSparse_; // dense position -> handle.index (for fixing up)
std::vector<std::uint32_t> free_;
public:
std::vector<Particle> dense; // packed, no holes: iterate this
Handle add(Particle p) {
std::uint32_t s;
if (!free_.empty()) { s = free_.back(); free_.pop_back(); }
else { s = std::uint32_t(sparse_.size()); sparse_.push_back({0, 1, false}); }
sparse_[s].dense = std::uint32_t(dense.size());
sparse_[s].alive = true;
dense.push_back(p);
denseToSparse_.push_back(s);
return {s, sparse_[s].gen};
}
Particle* get(Handle h) {
if (h.index >= sparse_.size()) return nullptr;
Entry& e = sparse_[h.index];
return (e.alive && e.gen == h.gen) ? &dense[e.dense] : nullptr;
}
void remove(Handle h) {
if (!get(h)) return;
std::uint32_t hole = sparse_[h.index].dense, last = std::uint32_t(dense.size() - 1);
dense[hole] = dense[last]; // move the last element into the hole
denseToSparse_[hole] = denseToSparse_[last];
sparse_[denseToSparse_[hole]].dense = hole; // its handle now points at the hole
dense.pop_back();
denseToSparse_.pop_back();
sparse_[h.index].alive = false;
sparse_[h.index].gen++;
free_.push_back(h.index);
}
};
void print(const DensePool& pool) {
std::printf(" dense:");
for (auto& p : pool.dense) std::printf(" #%d", p.id);
std::printf("\n");
}
int main() {
DensePool pool;
std::vector<Handle> h;
for (int i = 0; i < 5; i++) h.push_back(pool.add({float(i), i}));
print(pool);
pool.remove(h[1]);
std::puts("after removing #1:");
print(pool);
std::printf(" handle of #4 still finds #%d\n", pool.get(h[4])->id);
std::printf(" handle of #1 finds %s\n", pool.get(h[1]) ? "something" : "nothing");
float sum = 0;
for (auto& p : pool.dense) sum += p.x; // tight loop over live data only
std::printf(" sum of x over %zu live particles = %.1f\n", pool.dense.size(), sum);
} dense: #0 #1 #2 #3 #4
after removing #1:
dense: #0 #4 #2 #3
handle of #4 still finds #4
handle of #1 finds nothing
sum of x over 4 live particles = 9.0
This is exactly the sparse set at the heart of EnTT-style ECS storage, which the Sparse-Set ECS lesson builds out. The order of the dense array changes on removal, so don't rely on it.
Typed handles
A handle to a texture must never be passed where a mesh handle is expected. Make each kind a distinct type, for example with a tag template, and the compiler refuses mixups at zero runtime cost:
template <class Tag> struct TypedHandle { std::uint32_t bits = 0; };
using TextureHandle = TypedHandle<struct TextureTag>;
using MeshHandle = TypedHandle<struct MeshTag>;
void bindTexture(TextureHandle h);
MeshHandle rock = meshes.load("rock.mesh");
// bindTexture(rock); // error: no conversion from MeshHandle to TextureHandleTest yourself
A missile holds a handle to an enemy that died; the slot was reused by a new enemy. What does get(handle) return?
- The new enemy
- nullptr, because the handle's generation no longer matches the slot's
- The old enemy's data
- It crashes
Why can a handle-based pool keep its objects densely packed while a pointer-based one cannot?
- Handles are smaller
- Nobody stores raw addresses, so the pool may move objects and only update its indirection table
- Dense arrays don't need memory
- Pointers can't point into arrays
What risk does a small generation field (e.g. 12 bits) carry?
- Handles become slower to compare
- After many reuses the generation wraps around and a very old handle could match again
- It limits the pool to 4096 objects
- It cannot be stored in files