Published on 2026-11-15
Can you create memory allocator without defining any types?
I recently had to write some operator new for some freestanding project, and realized that it could be overloaded for arbitrary types. This opens up some interesting possibilities.
First of all, here's the simplest allocator I can define this way:
[[nodiscard]] inline void* operator new(size_t size, std::span<std::byte>& span) noexcept {
if (size > span.size()) {
return nullptr;
}
std::byte* ptr = span.data();
span = span.subspan(size);
return ptr;
}
It's a simple bump allocator over some storage (which could be static, on the stack, allocated via mmap, taken from a parent allocator, etc.). It's too simple for many cases, but I'm quite fond of the leverage it provides for so little code.
Here's an example usage:
struct Data {
uint64_t x;
uint64_t y;
uint64_t z;
};
std::array<std::byte, 1024> buffer{};
std::span<std::byte> span{buffer};
auto* data = new (span) Data{
.x = 1,
.y = 2,
.z = 3,
};
A cool thing about this is that new can be overloaded for any types. For example, we could add an overload for a type like Arena, which could be directly be called in a placement new expression:
auto data = new (arena) int{3};
You can even use templated types, such as an object pool:
template <typename T>
struct Pool {
T* allocate();
};
template <typename T>
[[nodiscard]] inline void* operator new(size_t /*size*/, Pool<T>& pool) noexcept {
return pool.allocate();
}
The return type of your overload must be void*, but the compiler will typecheck the assignment anyway:
Pool<int> pool;
float* ptr = new (pool) int{3}; // Doesn't compile: good!
There are caveats to the above:
std::type_identity argument to operator new.In both cases, I would recommend using the allocator's API directly.
Even when those caveats do not apply, it is not clear to me that using operator new is better than calling the allocator API directly anyway (at least outside of metaprogramming).
To me, this is a similar decision to defining a conversion operator on a strong type and calling static_cast, versus just adding a value() member function: it may be a bit more "pure"/"clean" because it leverages native language features, but it's not as discoverable and straightforward.