You don’t have to write a completely new container class. You can stick with your STL containers, but change the second parameter of for example std::vector
to give it your custom allocator which allocates from a stack-buffer. The chromium authors wrote an allocator just for this:
https://chromium.googlesource.com/chromium/chromium/+/master/base/stack_container.h
It works by allocating a buffer where you say how big it is. You create the container and call container.reserve(buffer_size);
. If you overflow that size, the allocator will automatically get elements from the heap (since it is derived from std::allocator
, it will in that case just use the facilities of the standard allocator). I haven’t tried it, but it looks like it’s from google so i think it’s worth a try.
Usage is like this:
StackVector<int, 128> s;
s->push_back(42); // overloaded operator->
s->push_back(43);
// to get the real std::vector.
StackVector<int, 128>::ContainerType & v = s.container();
std::cout << v[0] << " " << v[1] << std::endl;