Skip to content

Instantly share code, notes, and snippets.

@Kronuz
Last active May 15, 2019 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kronuz/6383535eb2719fdf867e2042ca5dce72 to your computer and use it in GitHub Desktop.
Save Kronuz/6383535eb2719fdf867e2042ca5dce72 to your computer and use it in GitHub Desktop.
Memory Pool C++ Allocator
#pragma once
#include <cstddef> // for std::size_t
#include <deque> // for std::deque
#include <new> // for std::bad_alloc, std::nothrow_t, std::new_handler
namespace allocator {
constexpr std::size_t alignment = alignof(std::max_align_t);
template <typename _Tp>
class memory_pool_allocator {
public:
// type definitions
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef _Tp* pointer;
typedef const _Tp* const_pointer;
typedef _Tp& reference;
typedef const _Tp& const_reference;
typedef _Tp value_type;
private:
union alignas(alignment) memory_pool_block {
char value[sizeof(value_type)];
memory_pool_block* next;
};
std::deque<memory_pool_block> buffer;
memory_pool_block* next_free_block = nullptr;
public:
// rebind allocator to type _Tp1
template <class _Tp1>
struct rebind {
typedef memory_pool_allocator<_Tp1> other;
};
// allocate but don't initialize n elements
pointer allocate(size_type __n, const void* __hint = static_cast<const void*>(0)) {
if (__n != 1 || __hint) {
throw std::bad_alloc();
}
if (next_free_block) {
memory_pool_block* block = next_free_block;
next_free_block = block->next;
return reinterpret_cast<pointer>(&block->value);
}
buffer.emplace_back();
return reinterpret_cast<pointer>(&buffer.back().value);
}
// deallocate storage __p of deleted elements
void deallocate(pointer __p, size_type) {
auto block = reinterpret_cast<memory_pool_block*>(__p);
block->next = next_free_block;
next_free_block = block;
}
// initialize elements of allocated storage __p with value value
void construct(pointer __p, const_reference __val) {
::new(__p) value_type(__val);
}
// destroy elements of initialized storage __p
void destroy(pointer __p) {
__p->~value_type();
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment