Wayverb
allocator.h
1 #pragma once
2 
3 #include <cassert>
4 #include <memory>
5 
6 namespace util {
7 namespace aligned {
8 
9 template <typename T, std::size_t N = alignof(T)>
10 class allocator {
11  // helper type with the alignment we want
12  using aligned_type = std::aligned_storage_t<sizeof(T), N>;
13 
14 public:
15  // type to allocate
16  using value_type = T;
17 
18  // characteristics
19  using propagate_on_container_copy_assignment = std::true_type;
20  using propagate_on_container_move_assignment = std::true_type;
21 
22  // ensure basic special class methods are enabled
23  allocator() noexcept = default;
24  allocator(const allocator&) noexcept = default;
25  allocator& operator=(const allocator&) noexcept = default;
26  allocator(allocator&&) noexcept = default;
27  allocator& operator=(allocator&&) noexcept = default;
28 
29  // allow construction from an allocator for another type
30  // (with the same alignment)
31  template <typename U>
32  allocator(const allocator<U>&) noexcept {}
33 
34  // implementations may derive from the allocator polymorphically
35  virtual ~allocator() noexcept = default;
36 
37  // rebinding the allocator for another type should respect the alignment
38  // of that other type
39  template <typename U>
40  struct rebind final {
41  using other = allocator<U>;
42  };
43 
44  // allocate a type that we know will have the correct alignment
45  // then reinterpret the pointer
46  T* allocate(std::size_t n) const {
47  return reinterpret_cast<T*>(new aligned_type[n]);
48  }
49 
50  // deallocate previously allocated memory
51  void deallocate(T* p, std::size_t s) const noexcept {
52  delete[] reinterpret_cast<aligned_type*>(p);
53  }
54 };
55 
56 template <typename T, typename U, std::size_t N>
57 constexpr bool operator==(const allocator<T, N>&,
58  const allocator<U, N>&) noexcept {
59  return true;
60 }
61 
62 template <typename T, typename U, std::size_t N>
63 constexpr bool operator!=(const allocator<T, N>&,
64  const allocator<U, N>&) noexcept {
65  return false;
66 }
67 
68 } // namespace aligned
69 } // namespace util
Definition: allocator.h:6
Definition: allocator.h:40
Definition: allocator.h:10