Skip to content

Instantly share code, notes, and snippets.

@kumar8600
Created July 21, 2015 09:41
Show Gist options
  • Save kumar8600/1d3cd64968def9b5beb8 to your computer and use it in GitHub Desktop.
Save kumar8600/1d3cd64968def9b5beb8 to your computer and use it in GitHub Desktop.
#pragma once
#include <cstddef>
#include <memory>
namespace kumar
{
struct dynamic_allocator_interface
{
virtual ~dynamic_allocator_interface() = default;
virtual void* allocate(std::size_t n) = 0;
virtual void deallocate(void* p, std::size_t n) = 0;
virtual void copy_construct(void* p, const void* src) = 0;
virtual void move_construct(void* p, void* src) = 0;
virtual void destroy(void* p) = 0;
};
template <typename T, typename Allocator>
struct dynamic_allocator : dynamic_allocator_interface
{
dynamic_allocator(const Allocator& allocator = Allocator()) :
allocator_(allocator)
{
}
virtual void* allocate(std::size_t n) override
{
return std::allocator_traits<Allocator>::allocate(allocator_, n);
}
virtual void deallocate(void * p, std::size_t n) override
{
std::allocator_traits<Allocator>::deallocate(allocator_, static_cast<T*>(p), n);
}
virtual void copy_construct(void* p, const void* src) override
{
const T& ref = *static_cast<const T*>(src);
std::allocator_traits<Allocator>::construct(allocator_, static_cast<T*>(p), ref);
}
virtual void move_construct(void* p, void* src) override
{
T& ref = *static_cast<T*>(src);
std::allocator_traits<Allocator>::construct(allocator_, static_cast<T*>(p), std::move(ref));
}
virtual void destroy(void* p) override
{
std::allocator_traits<Allocator>::destroy(allocator_, static_cast<T*>(p));
}
private:
Allocator allocator_;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment