Search code examples
c++memory-managementdynamic-memory-allocation

C++ allocator to store objects of different types


I have a bunch of objects wrapped by unique_ptrs.
Each object is of its own type.
I would like to create a kind of memory pool to store all those objects to avoid heap allocations for every last object. Like this:

Allocator allocator(1024); // should be extendable
unique_ptr< A > a = allocator.allocateAndWrapToUPtr< A >();
unique_ptr< B > b = allocator.allocateAndWrapToUPtr< B >();
C* c = allocator.allocate< C >();

As far as I can see allocators are specified as
template
class MyAllocator;
Hence they can store only objects of only one type.

Is it possible to implement "multitype" allocator?


Solution

  • It is not possible to use one allocator everywhere around the project. Dynamic allocator example can be found at dmitrysoshnikov.com/compilers/writing-a-pool-allocator, it allows to solve the initial problem with unique_ptrs.
    But it is not stl compliant so can not be used for collections for example.