October 16, 2025 nullprogram.com/blog/2025/10/16/ As I continue to reflect on arenas and lifetimes in C++, I realized that dealing with destructors is not so onerous. In fact, it does not even impact my established arena usage! That is, implicit RAII-style deallocation at scope termination, which works even in plain old C. With a small change we can safely place resource-managing objects in arenas, such as those owning file handles, sockets, threads, etc. (Though the ideal remains [resource management avoidance][swr] when possible.) We can also place traditional, memory-managing C++ objects in arenas, too. Their own allocations won’t come from the arena — either because they lack the interfaces to do so, or they’re simply ineffective at it (pmr) — but they will reliably clean up after themselves. It’s all exception-safe, too. In this article I’ll update my arena allocator with this new feature. The change requires one additional arena pointer member, a bit of overhead for objects with non-trivial destructors, and no impact for other objects. I continue to title this “speculations” because, unlike arenas in C, I have not (yet?) put these C++ techniques into practice in real software. I haven’t refined them through use. Even ignoring its standard library as I do here, C++ is an enormously complex programming language — far more so than C — and I’m less confident that I’m not breaking a rule by accident. I only want to break rules with intention! As a reminder here’s where we left things off: struct Arena { char *beg; char *end; }; template<typename T> T *raw_alloc(Arena *a, ptrdiff_t count = 1) { ptrdiff_t size = sizeof(T); ptrdiff_t pad = -(uintptr_t)a->beg & (alignof(T) - 1); if (count >= (a->end - a->beg - pad)/size) { throw std::bad_alloc{}; // OOM policy } void *r = a->beg + pad; a->beg += pad + count*size; return new(r) T[count]{}; } I used throw when out of memory mainly to emphasize that this works, but you’re free to pick whatever is appropriate for your prog...
First seen: 2025-10-23 06:29
Last seen: 2025-10-23 07:29