Facebook Pixel

You are on level: Student

0%
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section
Expand section

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 N slots of sizeof(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 (nullptr in 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) runs T's constructor on the memory at addr and returns a T*. Unlike plain new, it asks the allocator for nothing.
  • Explicit destructor call: p->~T() runs the destructor of the object at p and leaves its memory where it is.

What to implement

  • Write the class template ObjectPool<T, N> at global scope. It has room for exactly N objects of type T.
  • 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, and std::size_t are available. #include any 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.
MemberContractCalled by
ObjectPool()Builds the free list over all N slots, slot 0 on top.pool, widepool
ObjectPool(const ObjectPool&) = delete and operator=(const ObjectPool&) = deleteCopying 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() constThe 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&&... args is a parameter pack: create accepts any number of arguments of any types, and args... expands to all of them in order, so T(args...) hands them to T's constructor.
  • Part 1 always calls create with one int. Part 3 refines how the arguments are passed on.
  • The driver calls available through a const reference.
  • The driver checks at compile time that the pool cannot be copied, that create returns T*, and that available is a const member returning std::size_t. A failed check is a compile error in driver.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 create returned 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.
CommandWhat the driver runsPrints
pool P nObjectPool<Tracked, n> P; with 1 <= n <= 8nothing
create x P idTracked* x = P.create(id); where x is absent or holds nullptrevents, then x slot k, or x null when create returns nullptr
destroy xP.destroy(x); on the pool that created x, even when x holds nullptr. x becomes absent.events
avail PP.available()avail P n
heapReads the driver's heap counter.heap n
  • x slot k names the slot the returned pointer points at. A pointer that is not the start of one of the pool's slots prints x outside, which a correct pool never produces.
  • heap n counts every call to the global operator new or operator 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 prints heap 0.
  • The driver never returns memory to the system, so a stray delete of a slot shows up in that count instead of crashing.
  • After the last command the driver prints end. It then calls destroy on 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.

EventPrinted when a Tracked is
ctor idconstructed from an id
copy id or move idcopy or move constructed
dtor iddestroyed

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.

  1. The slab is stored inside the pool object itself, so building a pool allocates nothing, and neither does anything else the pool does.
  2. Declare the slab as the class's first data member and pack the slots with no gaps, so that slot i starts exactly i * sizeof(T) bytes after the pool's own address. The driver turns every pointer create returns into a slot index that way.
  3. A slot is either free or holds one live T. The free slots form the intrusive free list.
  4. A fresh pool's free list holds slots 0, 1, ..., N-1 in that order, with slot 0 on top.
  5. create pops the top slot and destroy pushes the freed slot on top, so the slot freed most recently is the next one reused (last in, first out, or LIFO).
  6. Objects go into a slot by placement new and come out by an explicit destructor call. delete p on a slot is a bug, since p never came from new.
  • 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) and alignof(Wide) are both 32, so every Wide must start at an address that is a multiple of 32.
  • Wide(id) constructs its Tracked, which prints ctor id, and destroying a Wide prints dtor id.
  • create, destroy, and avail work on Wide pools exactly as on Tracked pools.
CommandWhat the driver runsPrints
widepool W nObjectPool<Wide, n> W; with 1 <= n <= 8nothing
aligned PChecks every pointer P.create has returned so far.aligned P yes if each is a multiple of alignof(T), otherwise aligned P no
  1. A slot is aligned only if the slab is. An unsigned char array has alignment 1, so a byte slab needs alignas(T), the same fix as the alignas(WireUpdate) receive buffer in C++ Casts and Type Safety.
  2. Because the slab is the pool's first member, its alignment also becomes the pool's.
  3. 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. So T(args...) copies even when the caller passed an rvalue.
  • Args&& written on a template parameter is a forwarding reference. For an lvalue argument Args is deduced as Tracked&, and for an rvalue argument as plain Tracked.
  • 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.
CommandWhat the driver runsPrints
copyin x P idTracked src(id); Tracked* x = P.create(src); on a Tracked pool, then src goes out of scopector id, the pool's events, x slot k or x null, then dtor id
movein x P idTracked src(id); Tracked* x = P.create(std::move(src)); on a Tracked pool, then src goes out of scopethe same
  • A correct pool prints copy id for copyin and move id for movein, and neither when the pool is full.
  • The copy keeps the id, so the pooled object and src each print their own dtor id.

Tests 8–10 cover this part.

Example
Input
7
pool P 2
create a P 1
create b P 2
create c P 3
destroy a
create d P 4
avail P
Output
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
Explanation

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).