libcaramel
memory_allocator.hpp
1 #pragma once
2 
3 #include <cstddef>
4 
6 #include <libcaramel/util/crtp.hpp>
7 #include <libcaramel/util/types.hpp>
8 
9 #include <gsl/pointers>
10 
11 namespace caramel
12 {
13  template <typename Any>
15  {
16  public:
17  using pointer = Any*;
18  using const_pointer = const Any*;
19 
20  public:
21  memory_allocator() noexcept : mp_resource(get_default_memory_resource()) {}
22  memory_allocator(memory_resource* p_resource) noexcept : mp_resource{p_resource} {}
23  template <typename U>
24  memory_allocator(const memory_allocator<U>& other) noexcept : mp_resource{other.resource()}
25  {}
26 
27  auto operator==(const memory_allocator& alloc) const -> bool
28  {
29  return *resource() == *alloc.resource();
30  }
31 
32  auto allocate(count_t count) -> pointer
33  {
34  return static_cast<pointer>(
35  mp_resource->allocate(count_t{sizeof(Any)} * count, align_t{alignof(Any)}));
36  }
37  void deallocate(gsl::not_null<pointer> ptr, count_t count)
38  {
39  mp_resource->deallocate(gsl::make_not_null(static_cast<memory_resource::pointer>(ptr)),
40  count_t{sizeof(Any)} * count, align_t{alignof(Any)});
41  }
42 
43  auto resource() noexcept -> memory_resource* { return mp_resource; }
44 
45  private:
46  memory_resource* mp_resource{nullptr};
47  };
48 } // namespace caramel
Definition: memory_allocator.hpp:15
Abstract class defining the interface of a memory resource.
Definition: memory_resource.hpp:23
virtual auto allocate(count_t bytes, align_t alignment) noexcept -> pointer=0
Pure virtual function for a common allocation interface.
virtual void deallocate(gsl::not_null< pointer > ptr, count_t bytes, align_t alignment) noexcept=0
Pure virtual function for a common deallocation interface.
void * pointer
alias for ease of naming
Definition: memory_resource.hpp:25
Definition: strong_type.hpp:12