Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Object pools, arenas, and stale pointers after address reuse

A pool reuses individual slots; a monotonic arena reclaims storage in bulk. A generation-tagged handle distinguishes a new object from an old one at the same address.

Version: ISO C++23; implementation support may vary

Syntax

ISO C++23; implementation support may vary. For a single object in suitably sized and aligned storage: `T* p = ::new (static_cast<void*>(storage)) T(args...);` (`<new>`), then `std::destroy_at(p);` (`<memory>`) while the object is live. Keep the storage for reuse. Pool pattern: `create(...) -> std::optional<Handle>`, `get(Handle) -> T*`, `erase(Handle) -> bool`, with `Handle = {slot index, generation}`. These are example API signatures, not standard library interfaces. Arena example: `std::pmr::monotonic_buffer_resource` (`<memory_resource>`).

The phrase “object pool, arena and stale pointer reuse” connects two storage strategies with a lifetime trap. In C++23, a fixed-capacity object pool can keep objects of one type in fixed-size slots. Each slot has its own object lifetime: placement ::new constructs in suitably sized and aligned storage, and std::destroy_at destroys the object without releasing the slot. The pool destructor destroys any remaining live objects.

A monotonic arena, such as std::pmr::monotonic_buffer_resource, groups allocations for a phase. Individual deallocation does nothing; release() returns blocks to the upstream resource and resets the resource to its initial state. It does not call the destructors of user objects. Destroy objects and containers that still use its storage before resetting or destroying the resource.

Between destruction and reconstruction, do not access the object through the old pointer. With transparent replacement, as for two complete, non-const Item objects at the exact same location, the old pointer automatically refers to the new object. Pointer == cannot distinguish generations. If replacement is not transparent, do not assume automatic retargeting; use the pointer returned by construction. std::launder has its own preconditions and does not check logical identity.

The example uses a bounded linear scan: create checks at most N slots (O(N) worst case) and returns std::nullopt if no slot is usable. It is neither a constant-time allocator nor an implementation of the standard allocator interface. get and erase check the index, generation, and live state. Once the maximum generation has been used, the slot is retired on erasure so the counter cannot wrap.

Use handles only with the same, still-live pool instance. A returned raw pointer is borrowed: it neither extends the object's lifetime nor performs later checks. If threads share the pool, synchronize both pool operations and access through borrowed pointers externally.

Examples

#include <array>
#include <cstddef>
#include <iostream>
#include <limits>
#include <memory>
#include <new>
#include <optional>

struct Item {
    int value;
};

class Pool {
public:
    struct Handle {
        std::size_t index;
        unsigned generation;
    };

    Pool() = default;
    Pool(const Pool&) = delete;
    Pool& operator=(const Pool&) = delete;
    Pool(Pool&&) = delete;
    Pool& operator=(Pool&&) = delete;

    ~Pool() {
        for (auto& slot : slots_) {
            if (slot.live) std::destroy_at(slot.live);
        }
    }

    std::optional<Handle> create(int value) {
        for (std::size_t i = 0; i < slots_.size(); ++i) {
            auto& slot = slots_[i];
            if (slot.live || slot.generation == std::numeric_limits<unsigned>::max()) {
                continue; // A slot at the maximum generation cannot be reused.
            }
            slot.live = ::new (static_cast<void*>(slot.storage)) Item{value};
            ++slot.generation;
            return Handle{i, slot.generation};
        }
        return std::nullopt;
    }

    Item* get(Handle h) noexcept {
        if (h.index >= slots_.size()) return nullptr;
        auto& slot = slots_[h.index];
        return slot.generation == h.generation ? slot.live : nullptr;
    }

    bool erase(Handle h) noexcept {
        if (Item* p = get(h)) {
            std::destroy_at(p);
            slots_[h.index].live = nullptr;
            return true;
        }
        return false;
    }

private:
    struct Slot {
        alignas(Item) std::byte storage[sizeof(Item)];
        Item* live = nullptr;
        unsigned generation = 0;
    };
    std::array<Slot, 2> slots_{};
};

int main() {
    Pool pool;
    const auto old = pool.create(10).value();
    Item* const first = pool.get(old);
    pool.create(20).value();

    std::cout << std::boolalpha;
    std::cout << "full: " << !pool.create(30).has_value() << '\n';
    pool.erase(old);
    const auto fresh = pool.create(40).value();
    Item* const current = pool.get(fresh);

    std::cout << "same address: " << (first == current) << '\n';
    std::cout << "stale handle rejected: " << (pool.get(old) == nullptr) << '\n';
    std::cout << "fresh value: " << current->value << '\n';
}

Result

full: true
same address: true
stale handle rejected: true
fresh value: 40

After filling both slots, the program destroys the first object and constructs `Item{40}` in that same slot. It compares pointers only after reconstruction; the old handle is rejected even though the address matches.

Related lessons

  • C++ · Lesson 19 · Advanced · Version: 3

Sources