Fixed-Capacity Containers and Ring Buffers
std::vector grows when it needs to, which means it may allocate at any push_back. In engine code that runs every frame, unbounded growth is a hidden cost and a hidden risk: an allocation spike in the middle of combat, or memory use that creeps up over a long session. Engines lean on fixed-capacity containers: the maximum size is decided up front, memory is reserved once, and "full" is an explicit, handled condition.
| Container | Use | Standard or library equivalent |
|---|---|---|
| Fixed vector (inline storage, max N) | contacts per body, lights per cluster, bones per vertex | std::inplace_vector (C++26), boost::container::static_vector, EASTL fixed_vector |
| Fixed string | names, short paths without heap use | std::array<char, N>, EASTL fixed_string |
| Ring buffer (circular queue) | event queues, log history, frame-time graphs, input history for replays, audio sample buffers, work queues between threads | boost::circular_buffer; none in std |
| Fixed hash map | small lookup tables per frame | open addressing in a std::array |
The ring buffer
A ring buffer is an array plus two counters: where to write next (head) and where to read next (tail). Both only ever increase; the array slot is counter % capacity. When the capacity is a power of two, % capacity becomes & (capacity - 1), a single AND instruction.
capacity 4, after pushing A B C D, popping twice (A, B), then pushing E F:
slot: 0 1 2 3
data: [ E ][ F ][ C ][ D ] tail = 2 (C is oldest), head = 6
size = head - tail = 4Keeping counters that never wrap back to zero (rather than indices that do) makes size = head - tail correct even when the buffer is full, without a separate "full" flag. With 64-bit counters they won't overflow in the lifetime of any game. With 32-bit unsigned counters even overflow is harmless: unsigned subtraction wraps too, so head - tail stays right as long as the capacity is a power of two.
#include <array>
#include <cstdint>
#include <cstdio>
#include <initializer_list>
#include <optional>
template <class T, std::size_t N>
class RingBuffer {
static_assert((N & (N - 1)) == 0, "capacity must be a power of two");
std::array<T, N> data_{};
std::uint64_t head_ = 0, tail_ = 0; // monotonically increasing counters
public:
std::size_t size() const { return std::size_t(head_ - tail_); }
bool empty() const { return head_ == tail_; }
bool full() const { return size() == N; }
bool tryPush(const T& v) { // queue semantics: reject when full
if (full()) return false;
data_[head_++ & (N - 1)] = v;
return true;
}
void pushOverwrite(const T& v) { // history semantics: drop the oldest
if (full()) tail_++;
data_[head_++ & (N - 1)] = v;
}
std::optional<T> pop() {
if (empty()) return std::nullopt;
return data_[tail_++ & (N - 1)];
}
const T& operator[](std::size_t i) const { return data_[(tail_ + i) & (N - 1)]; } // 0 = oldest
};
int main() {
RingBuffer<char, 4> queue;
for (char c : {'A', 'B', 'C', 'D', 'E'})
std::printf("push %c: %s\n", c, queue.tryPush(c) ? "ok" : "rejected (full)");
char first = *queue.pop();
char second = *queue.pop();
std::printf("pop %c, pop %c\n", first, second);
queue.tryPush('E');
queue.tryPush('F');
std::printf("contents oldest->newest:");
for (std::size_t i = 0; i < queue.size(); i++) std::printf(" %c", queue[i]);
std::printf(" (size %zu)\n", queue.size());
RingBuffer<int, 4> history; // keeps the last 4 values only
for (int v = 1; v <= 7; v++) history.pushOverwrite(v * 10);
std::printf("history:");
for (std::size_t i = 0; i < history.size(); i++) std::printf(" %d", history[i]);
std::printf("\n");
}push A: ok
push B: ok
push C: ok
push D: ok
push E: rejected (full)
pop A, pop B
contents oldest->newest: C D E F (size 4)
history: 40 50 60 70
Two policies cover almost every use:
- Reject when full for queues where every element matters (events, jobs, network messages). The producer must handle failure: block, drop with a warning, or flush.
- Overwrite the oldest for history where only recent data matters (the console log, a frame-time graph, the last few seconds of input for a kill-cam or bug report).
A frame-time history
Debug overlays show the last few hundred frame times as a graph and report the average and the worst frame. A ring buffer with a running sum does this in constant time per frame, with no allocation:
#include <array>
#include <cstdio>
#include <vector>
template <std::size_t N>
struct FrameHistory {
std::array<double, N> ms{};
std::size_t count = 0, next = 0;
double sum = 0;
void add(double v) {
if (count == N) sum -= ms[next]; else count++; // remove the value being overwritten
ms[next] = v;
sum += v;
next = (next + 1) % N;
}
double average() const { return count ? sum / count : 0; }
double worst() const {
double w = 0;
for (std::size_t i = 0; i < count; i++) w = ms[i] > w ? ms[i] : w;
return w;
}
};
int main() {
FrameHistory<8> h;
// scripted frame times in ms: steady 60 FPS, a 45 ms hitch, then recovery
std::vector<double> frames = {16.7, 16.6, 16.8, 16.7, 45.0, 16.7, 16.6, 16.7, 16.8, 16.7, 16.6, 16.7, 16.7};
for (std::size_t f = 0; f < frames.size(); f++) {
h.add(frames[f]);
if (f % 4 == 0 || f == frames.size() - 1)
std::printf("frame %2zu: avg %.2f ms, worst of last %zu: %.1f ms\n", f, h.average(), h.count, h.worst());
}
}frame 0: avg 16.70 ms, worst of last 1: 16.7 ms
frame 4: avg 22.36 ms, worst of last 5: 45.0 ms
frame 8: avg 20.24 ms, worst of last 8: 45.0 ms
frame 12: avg 16.69 ms, worst of last 8: 16.8 ms
The hitch dominates the "worst" column for exactly 8 frames, then drops out of the window. This is why overlays show both: the average hides stutters that players notice immediately. Recomputing sum from scratch now and then prevents floating-point drift from the repeated add/subtract in a long session.
Ring buffers between threads
A ring buffer with exactly one producer and one consumer (SPSC) can be made lock-free with two atomic counters: the producer alone writes head, the consumer alone writes tail. It is the standard way to pass audio samples to the audio callback, log lines to a writer thread, or commands to a render thread. The Lock-Free Queues and False Sharing lesson builds one with std::atomic and explains the memory ordering. Multiple producers or consumers need a more careful design or a well-tested library (moodycamel::ConcurrentQueue, rigtorp::SPSCQueue).
Fixed vectors
The other workhorse is a vector with inline storage and a maximum size: no heap, contiguous memory, and a clear error when exceeded. C++26 standardizes it as std::inplace_vector<T, N>; until your compilers support it, a small hand-written one or a library version does the job.
template <class T, std::size_t N>
class FixedVector {
alignas(T) std::byte storage_[N * sizeof(T)];
std::size_t size_ = 0;
public:
bool push_back(const T& v) {
if (size_ == N) return false; // caller handles "full"
new (storage_ + size_ * sizeof(T)) T(v);
++size_;
return true;
}
T& operator[](std::size_t i) { return *std::launder(reinterpret_cast<T*>(storage_ + i * sizeof(T))); }
std::size_t size() const { return size_; }
~FixedVector() { for (std::size_t i = 0; i < size_; i++) (*this)[i].~T(); }
// copy/move omitted for brevity
};
// e.g. at most 4 bone influences per vertex, at most 8 lights per tile
FixedVector<int, 8> lightsInTile;Test yourself
Why can a ring buffer compute its size as head - tail even when full?
- Because it stores a separate full flag
- Because the counters keep increasing and are only reduced modulo the capacity when indexing
- Because capacity is always 1 less than the array size
- Because head never passes tail
Which policy suits a console log history shown in the debug overlay?
- Reject new lines when full
- Overwrite the oldest line when full
- Grow without limit
- Clear everything when full
Why should the capacity be a power of two?
- Caches require it
- The slot index can then be computed with a bitwise AND instead of a modulo
- Atomics only work on powers of two
- It doubles the capacity for free