Fixed-Size Pool Allocator
Prerequisites: pmr, Allocators, and Object Pools, Allocation in the Hot Path, Small Buffer Optimization, C++ Casts and Type Safety
A strategy creates an Order when it sends a new $AAPL order and destroys it when the order fills or is canceled. If every Order comes from new, every new order calls the allocator, and the allocator's slow path can land on any of them.
The object pool from pmr, Allocators, and Object Pools removes that call. It reserves all of its memory when it is built, and creating or destroying an object afterwards only moves a pointer. Build one.
- Slab: the pool's memory, one block of
Nslots ofsizeof(T)bytes each. - Intrusive free list: the free slots kept as a stack, where each free slot stores, in its own bytes, a pointer to the next free slot (
nullptrin the last one). The pool keeps only a pointer to the top slot, called the head. - Placement new:
::new (static_cast<void*>(addr)) T(args)runsT's constructor on the memory ataddrand returns aT*. Unlike plainnew, it asks the allocator for nothing. - Explicit destructor call:
p->~T()runs the destructor of the object atpand leaves its memory where it is.
What to implement
- Write the class template
ObjectPool<T, N>at global scope. It has room for exactlyNobjects of typeT. - You write only the class, and the editor already declares every member the driver calls. A hidden driver instantiates it with driver types, runs it through a list of commands, and prints what happened.
<new>,<utility>, and<cstddef>are already included, so placement new,std::forward, andstd::size_tare available.#includeany other header you need at the top of your code.- On stdin, the first line is the number of commands, and each remaining line is one command.
- There are three parts. One solution must pass all ten tests.
| Member | Contract | Called by |
|---|---|---|
ObjectPool() | Builds the free list over all N slots, slot 0 on top. | pool, widepool |
ObjectPool(const ObjectPool&) = delete and operator=(const ObjectPool&) = delete | Copying does not compile: a copy's free list would point into the original's slab. | compile-time check |
template <class... Args> T* create(Args&&... args) | If no slot is free, returns nullptr and constructs nothing. Otherwise pops the top slot, constructs a T in it from args, and returns a pointer to that T. | create, copyin, movein |
void destroy(T* p) | If p is nullptr, does nothing. Otherwise runs p's destructor and pushes its slot onto the free list. A non-null p is always a pointer this pool's create returned that has not been destroyed since. | destroy, end of input |
std::size_t available() const | The number of free slots. | avail |
~ObjectPool() | Destroys nothing: the driver destroys every live object before a pool goes out of scope. | end of input |
Args&&... argsis a parameter pack:createaccepts any number of arguments of any types, andargs...expands to all of them in order, soT(args...)hands them toT's constructor.- Part 1 always calls
createwith oneint. Part 3 refines how the arguments are passed on. - The driver calls
availablethrough aconstreference. - The driver checks at compile time that the pool cannot be copied, that
createreturnsT*, and thatavailableis aconstmember returningstd::size_t. A failed check is a compile error indriver.cpp(the hidden driver) whose message names the rule.
Commands
- Each command is one line. Pools are named by one uppercase letter.
- Objects are named by one lowercase letter, a handle that remembers the pointer
createreturned and the pool that returned it. - Ids are positive integers, and every command that constructs an object uses a new id. Every command is valid for the names it uses.
| Command | What the driver runs | Prints |
|---|---|---|
pool P n | ObjectPool<Tracked, n> P; with 1 <= n <= 8 | nothing |
create x P id | Tracked* x = P.create(id); where x is absent or holds nullptr | events, then x slot k, or x null when create returns nullptr |
destroy x | P.destroy(x); on the pool that created x, even when x holds nullptr. x becomes absent. | events |
avail P | P.available() | avail P n |
heap | Reads the driver's heap counter. | heap n |
x slot knames the slot the returned pointer points at. A pointer that is not the start of one of the pool's slots printsx outside, which a correct pool never produces.heap ncounts every call to the globaloperator neworoperator delete, in any form, made inside the pool's members so far, the constructor and destructor included. The driver's own allocations are not counted. A correct pool always printsheap 0.- The driver never returns memory to the system, so a stray
deleteof a slot shows up in that count instead of crashing. - After the last command the driver prints
end. It then callsdestroyon every object that is still live, in the order the objects were created, and finally destroys the pools in reverse order of creation.
The Tracked type
The events come from Tracked, a driver type that holds a long long id, so it is 8 bytes and 8-byte aligned.
| Event | Printed when a Tracked is |
|---|---|
ctor id | constructed from an id |
copy id or move id | copy or move constructed |
dtor id | destroyed |
It cannot be assigned, so the only way to put a Tracked into a slot is to construct it there.
Part 1: A pool of Tracked objects
Implement the members in the table for ObjectPool<Tracked, N>, following these rules.
- The slab is stored inside the pool object itself, so building a pool allocates nothing, and neither does anything else the pool does.
- Declare the slab as the class's first data member and pack the slots with no gaps, so that slot
istarts exactlyi * sizeof(T)bytes after the pool's own address. The driver turns every pointercreatereturns into a slot index that way. - A slot is either free or holds one live
T. The free slots form the intrusive free list. - A fresh pool's free list holds slots
0, 1, ..., N-1in that order, with slot0on top. createpops the top slot anddestroypushes the freed slot on top, so the slot freed most recently is the next one reused (last in, first out, or LIFO).- Objects go into a slot by placement new and come out by an explicit destructor call.
delete pon a slot is a bug, sincepnever came fromnew.
- No separate container is needed for the free list, because a free slot's bytes are unused anyway.
- Every type the driver pools is at least as large and as aligned as a pointer, which the starter checks with a
static_assert, so the link always fits. - The object's lifetime, in the sense of Object Lifetime, runs from the placement new to the destructor call, while the slot's bytes stay in the slab.
Tests 1–5 cover this part: the order of a fresh pool, LIFO reuse after interleaved destroys, a full pool, destroy(nullptr), destroys in the middle of the slab, and two pools that keep separate free lists.
Part 2: Over-aligned types
The driver adds Wide, declared struct alignas(32) Wide, which holds one Tracked.
sizeof(Wide)andalignof(Wide)are both 32, so everyWidemust start at an address that is a multiple of 32.Wide(id)constructs itsTracked, which printsctor id, and destroying aWideprintsdtor id.create,destroy, andavailwork onWidepools exactly as onTrackedpools.
| Command | What the driver runs | Prints |
|---|---|---|
widepool W n | ObjectPool<Wide, n> W; with 1 <= n <= 8 | nothing |
aligned P | Checks every pointer P.create has returned so far. | aligned P yes if each is a multiple of alignof(T), otherwise aligned P no |
- A slot is aligned only if the slab is. An
unsigned chararray has alignment 1, so a byte slab needsalignas(T), the same fix as thealignas(WireUpdate)receive buffer in C++ Casts and Type Safety. - Because the slab is the pool's first member, its alignment also becomes the pool's.
- The driver constructs each pool at the least-aligned address its type allows: a multiple of
alignof(ObjectPool<T, N>)that is not a multiple of twice that. A slab that would reach a 32-byte boundary only by luck is therefore caught.
Tests 6–7 cover this part.
Part 3: Forwarding constructor arguments
A pool should construct each object the way the caller asked. Given a named Tracked src, P.create(src) should copy src into the slot and P.create(std::move(src)) should move it, as in Move Semantics Without Magic.
- Inside
create, though, every argument has a name,args, and a named variable is an lvalue. SoT(args...)copies even when the caller passed an rvalue. Args&&written on a template parameter is a forwarding reference. For an lvalue argumentArgsis deduced asTracked&, and for an rvalue argument as plainTracked.std::forward<Args>(args)uses that record to cast the argument back: it yields an rvalue exactly when the caller passed one.T(std::forward<Args>(args)...)therefore passes every argument on with the value category the caller gave it. This is called perfect forwarding.
| Command | What the driver runs | Prints |
|---|---|---|
copyin x P id | Tracked src(id); Tracked* x = P.create(src); on a Tracked pool, then src goes out of scope | ctor id, the pool's events, x slot k or x null, then dtor id |
movein x P id | Tracked src(id); Tracked* x = P.create(std::move(src)); on a Tracked pool, then src goes out of scope | the same |
- A correct pool prints
copy idforcopyinandmove idformovein, and neither when the pool is full. - The copy keeps the id, so the pooled object and
srceach print their owndtor id.
Tests 8–10 cover this part.
7 pool P 2 create a P 1 create b P 2 create c P 3 destroy a create d P 4 avail P
ctor 1 a slot 0 ctor 2 b slot 1 c null dtor 1 ctor 4 d slot 0 avail P 0 end dtor 2 dtor 4
A fresh pool hands out slot 0 and then slot 1. The pool is then full, so create c P 3 returns nullptr without constructing object 3.
destroy a runs object 1's destructor and pushes slot 0, which create d P 4 reuses.
At the end the driver destroys the live objects in creation order: b (object 2), then d (object 4).