Created
July 21, 2015 09:41
-
-
Save kumar8600/1d3cd64968def9b5beb8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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