foonathan / memory

STL compatible C++ memory allocator library using a new RawAllocator concept that is similar to an Allocator but easier to use and write.

Home Page:https://memory.foonathan.net

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

memory_arena with fixed size preallocated storage?

kevin-- opened this issue · comments

I'm intending to have a preallocated block of memory that I can partition into non-trivial objects, and was thinking to use the memory_arena allocator with a static_block_allocator

template <size_t Capacity, size_t WorseCaseObjectSize>
struct ObjectArena
{
    using static_arena_t = memory::memory_arena<memory::static_block_allocator>;
    static_arena_t mArena;
    
    constexpr static size_t SizeBytes = static_arena_t::min_block_size(Capacity * WorseCaseObjectSize);
    memory::static_allocator_storage<SizeBytes> mStorage;

    ObjectArena()
    : mArena( SizeBytes, mStorage )
    {
    }
};

Then I want to allocate a shared_ptr<T> of some object:

ObjectArena arena;
...
auto ptr = memory::allocate_shared<T>( arena.mArena, std::forward(args)... );

and I'm facing this static_assert

static_assert(invalid_allocator_concept<Allocator>::error,
                              "type is not a RawAllocator as it does not provide: void* "
                              "allocate_node(std::size_t, "
                              "std::size_t)");

It doesn't seem to like the static_block_allocator. Is there a more appropriate way to accomplish this with the library that I'm overlooking?

A static_block_allocator, as the name suggests, is a BlockAllocator. Those are designed to just hand out big memory blocks when asked, so they can't be used for individual allocations.

To allocate small things, you need a RawAllocator that manages the memory of the BlockAllocator. Depending on your use case this can be a memory_stack<static_block_allocator> or a memory_pool<node_pool, static_block_allocator>.

The type memory_arena itself is mostly an implementation detail to store multiple blocks returned by a BlockAllocator. It is used internally by memory_stack and pool.