TExcelTAD
Home › Game Engine Architecture in C++ › RAII, Ownership and Lifetimes

RAII, Ownership and Lifetimes

An engine juggles thousands of objects whose lifetimes don't match the C++ scopes around them: GPU buffers, textures shared by many materials, sounds still playing after the entity that started them died, entities destroyed in the middle of a frame. Most engine crashes come down to one question asked badly: who owns this, and how long does it live?

This lesson assumes you know std::unique_ptr, std::shared_ptr and move semantics from the C++ course (Smart Pointers, Move Semantics). Here we look at how engines apply them.

Four kinds of reference

Kind C++ form Use in an engine
Unique owner value member, std::unique_ptr<T>, a move-only RAII wrapper subsystems, GPU objects owned by one renderer resource, a level's memory arena
Shared owner std::shared_ptr<T> or an intrusive reference count assets used by many things (a texture referenced by 30 materials); see Resource Cache
Borrowed T&, T*, std::span<T>, std::string_view function parameters and locals that must not outlive the call or frame
Handle a small integer ID with a generation references stored long-term to things that can die: entities, sounds, physics bodies; see Generational Handles

The rule of thumb: own with values and unique_ptr, pass by reference, store handles. A raw pointer kept in a component ("my target") is the classic engine bug: the target dies, its memory is reused, and the pointer now silently points at a different object.

RAII for things that aren't memory

Graphics APIs, audio libraries and the OS hand out resources by ID or opaque pointer: GLuint texture names, VkBuffer, ma_sound, file descriptors. Each must be released exactly once, with the right function, while the API is still alive. Wrap them in a move-only RAII type. The program below uses a fake "GPU API" that counts live objects, so we can see leaks and double frees:

cpp · try it yourself
#include <cstdio>
#include <utility>
#include <vector>

// ---- a pretend C graphics API (like glGenTextures / glDeleteTextures) ----
int gLive = 0, gNextId = 1;
unsigned apiCreateTexture(int w, int h) { gLive++; std::printf("  create texture %d (%dx%d)\n", gNextId, w, h); return gNextId++; }
void apiDestroyTexture(unsigned id) { gLive--; std::printf("  destroy texture %u\n", id); }

// ---- RAII wrapper: owns exactly one texture ----
class Texture {
    unsigned id_ = 0;
public:
    Texture() = default;
    Texture(int w, int h) : id_(apiCreateTexture(w, h)) {}
    ~Texture() { if (id_) apiDestroyTexture(id_); }

    Texture(const Texture&) = delete;                         // copying would double-free
    Texture& operator=(const Texture&) = delete;
    Texture(Texture&& o) noexcept : id_(std::exchange(o.id_, 0)) {}
    Texture& operator=(Texture&& o) noexcept {
        if (this != &o) {
            if (id_) apiDestroyTexture(id_);
            id_ = std::exchange(o.id_, 0);
        }
        return *this;
    }
    unsigned id() const { return id_; }
};

int main() {
    {
        std::puts("load level:");
        std::vector<Texture> textures;
        textures.reserve(2);
        textures.emplace_back(1024, 1024);
        textures.emplace_back(512, 512);
        Texture shadowMap(2048, 2048);

        std::puts("resize shadow map:");
        shadowMap = Texture(4096, 4096);                     // old one destroyed, new one owned

        std::puts("hand texture to another owner:");
        Texture moved = std::move(textures[0]);              // textures[0] now owns nothing
        std::printf("  textures[0].id = %u, moved.id = %u\n", textures[0].id(), moved.id());
        std::puts("unload level:");
    }                                                        // everything released here, once
    std::printf("live textures after unload: %d\n", gLive);
}
load level:
  create texture 1 (1024x1024)
  create texture 2 (512x512)
  create texture 3 (2048x2048)
resize shadow map:
  create texture 4 (4096x4096)
  destroy texture 3
hand texture to another owner:
  textures[0].id = 0, moved.id = 1
unload level:
  destroy texture 1
  destroy texture 4
  destroy texture 2
live textures after unload: 0

Every texture is destroyed exactly once, including the one replaced by move assignment, and the moved-from object holds 0 so its destructor does nothing. noexcept on the move operations matters: std::vector only moves elements during reallocation when the move constructor is noexcept; otherwise it copies, which a move-only type can't do.

unique_ptr with a custom deleter

For C libraries that already give you a pointer and a destroy function, std::unique_ptr with a deleter type is enough, with no class to write:

cpp
#include <SDL3/SDL.h>
#include <memory>

struct SdlWindowDeleter { void operator()(SDL_Window* w) const { SDL_DestroyWindow(w); } };
using WindowPtr = std::unique_ptr<SDL_Window, SdlWindowDeleter>;

WindowPtr window{SDL_CreateWindow("My Engine", 1280, 720, SDL_WINDOW_RESIZABLE)};
if (!window) { /* SDL_GetError() */ }
SDL_ShowWindow(window.get());

An empty deleter struct adds no size: sizeof(WindowPtr) == sizeof(SDL_Window*) on the major compilers.

Deferred destruction

GPU resources have one extra twist: the CPU records frame N+1 while the GPU is still drawing frame N. Destroying a buffer the moment the last CPU owner lets go can free memory the GPU is reading. Renderers therefore defer destruction: the RAII destructor pushes the resource onto a queue tagged with the current frame number, and the queue is flushed only after the GPU has signaled that frame complete (a fence in Vulkan/D3D12). The same idea applies to entities: "destroy" marks them, and the actual removal happens at a safe point at the end of the frame.

cpp · try it yourself
#include <cstdio>
#include <deque>

struct PendingDelete { unsigned id; unsigned long long frame; };

struct DeletionQueue {
    std::deque<PendingDelete> queue;
    void push(unsigned id, unsigned long long frame) { queue.push_back({id, frame}); }
    // GPU finished every frame <= completedFrame: safe to free those resources
    void collect(unsigned long long completedFrame) {
        while (!queue.empty() && queue.front().frame <= completedFrame) {
            std::printf("    free buffer %u (released in frame %llu)\n", queue.front().id, queue.front().frame);
            queue.pop_front();
        }
    }
};

int main() {
    const int framesInFlight = 2;               // CPU may run 2 frames ahead of the GPU
    DeletionQueue dq;
    for (unsigned long long frame = 1; frame <= 5; frame++) {
        std::printf("frame %llu\n", frame);
        if (frame == 1) dq.push(10, frame);     // last CPU owner dropped buffer 10
        if (frame == 2) { dq.push(11, frame); dq.push(12, frame); }
        unsigned long long gpuDone = frame > framesInFlight ? frame - framesInFlight : 0;
        dq.collect(gpuDone);
    }
}
frame 1
frame 2
frame 3
    free buffer 10 (released in frame 1)
frame 4
    free buffer 11 (released in frame 2)
    free buffer 12 (released in frame 2)
frame 5

Common lifetime bugs and their fixes

Bug Symptom Fix
Storing T* to an entity or component crash or wrong object after the target dies store a generational handle and check it every use
Pointer into a std::vector that grows dangling after push_back reallocates store an index or handle; reserve only if the size is truly fixed
Destroying during iteration skipped elements, invalid iterators mark for destruction, remove at end of frame
shared_ptr cycles (A holds B, B holds A) leak, never destroyed make one side weak_ptr or a handle
Static/global objects with destructors crash at exit (destroyed after the subsystem they use) explicit startup/shutdown, see Engine Layers
Releasing a GPU object the GPU still uses device lost, flicker, corruption deferred deletion queue keyed by frame

Tip: Run development builds with AddressSanitizer regularly (-fsanitize=address in GCC and Clang, /fsanitize=address in MSVC). It turns most use-after-free and out-of-bounds bugs from "random crash next week" into an exact report with both stack traces. See Toolkit: Debuggers, Sanitizers and Profilers.

Test yourself

Why are the Texture wrapper's copy operations deleted?

  1. Copies would be slow
  2. Two copies would both destroy the same texture ID (a double free)
  3. Textures cannot be stored in vectors otherwise
  4. The API forbids reading the ID

A component stores Enemy* target. The target is destroyed and its memory reused. What happens?

  1. The pointer becomes nullptr automatically
  2. The pointer silently refers to whatever object now occupies that memory
  3. The compiler reports an error
  4. The target is kept alive

Why do renderers delay destroying GPU resources by a few frames?

  1. To save CPU time
  2. Because the GPU may still be reading them for frames already submitted
  3. Because drivers are slow to allocate
  4. To make loading faster