Skip to content

Instantly share code, notes, and snippets.

@benloong
Created December 19, 2016 13:00
Show Gist options
  • Save benloong/2a0d8a41e2bde1897cd7e4f2b564df9d to your computer and use it in GitHub Desktop.
Save benloong/2a0d8a41e2bde1897cd7e4f2b564df9d to your computer and use it in GitHub Desktop.
simple pool allocator
#pragma once
#include<memory>
template<typename T, size_t ChunkSize = 1024>
struct pool_allocator
{
using alloc_type = T;
using pointer_type = alloc_type*;
pool_allocator()
{
}
~pool_allocator()
{
free_chunk();
}
pointer_type allocate()
{
if (free_block == nullptr)
{
alloc_chunk();
}
element* elem = free_block;
free_block = free_block->next_free;
return &(elem->item);
}
void free(pointer_type item)
{
element* p = (element*)item;
p->next_free = free_block->next_free;
free_block = p;
}
private:
void alloc_chunk()
{
chunk* p = (chunk*)std::malloc(sizeof(chunk));
p->next_chunk = chunks;
chunks = p;
for (size_t i = 0; i < ChunkSize - 1; i++)
{
p->pool[i].next_free = p->pool + i + 1;
}
p->pool[ChunkSize - 1].next_free = free_block;
free_block = (p->pool);
}
void free_chunk()
{
while (chunks)
{
chunk* next = chunks->next_chunk;
std::free(chunks);
chunks = next;
}
chunks = nullptr;
free_block = nullptr;
}
struct element
{
union
{
alloc_type item;
element* next_free;
};
};
struct chunk
{
chunk* next_chunk;
element pool[ChunkSize];
};
chunk* chunks = nullptr;
element* free_block = nullptr;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment