I was looking into how custom containers are created, such as eastl’s container and several other models and I see that they all use an “allocator”, much like std::vector does with std::allocator. Which got me thinking, why do new implementations of a vector container use an allocator when they typically have an underlying memory management override for new and delete?
I was looking into how custom containers are created, such as eastl’s container and
Share
Being able to replace
operator new()andoperator delete()(and their array versions) at program level may be sufficient for small program. If you have programs consisting of many millions lines of code, running many different threads this isn’t at all suitable. You often want or even need better control. To make the use of custom allocators effective, you also need to be able to allocate subobjects using the same objects as the outer allocator.For example, consider the use of memory arena to be used when answering a request in some sort of a server which is probably running multiple threads. Getting memory from
operator new()is probably fairly expensive because it involves allocating a lock and finding a suitable chunk of memory in a heap which is getting more and more fragmented. To avoid this, you just want to allocate a few chunks of memory (ideally just one but you may not know the needed size in advance) and put all objects there. An allocator can do this. To do so, you need to inform all entities allocating memory about this chunk of memory, i.e. you need to pass the allocator to everything possibly allocating memory. If you allocate e.g. astd::vector<std::string, A>thestd::stringobjects should know about the allocator: just telling thestd::vector<std::string, A>where and how to allocate memory isn’t enough to avoid most memory allocations: you also need to tell it to thestd::string(well, actually thestd::basic_string<char, std::char_traits<char>, B>for a suitable allocator typeBwhich is related toA).That is, if you really mean to take control of your memory allocations, you definitely want to pass allocators to everything which allocates memory. Using replaced versions of the global memory management facilities may help you but it is fairly constrained. If you just want to write a custom container and memory allocation isn’t much of your concern you don’t necessarily need to bother. In big systems which are running for extensive periods of time memory allocation is one of the many concerns, however.