Allocator Builder
Policy Based C++ Template Allocator Library
 All Classes Functions Variables Enumerations Enumerator Groups Pages
aligned_mallocator.hpp
1 //
3 // Copyright 2014 Felix Petriconi
4 //
5 // License: http://boost.org/LICENSE_1_0.txt, Boost License 1.0
6 //
7 // Authors: http://petriconi.net, Felix Petriconi
8 //
10 #pragma once
11 
12 #include "allocator_base.hpp"
13 #include "internal/reallocator.hpp"
14 
15 namespace alb {
16  inline namespace v_100 {
27  template <unsigned DefaultAlignment = 16> class aligned_mallocator {
28  static constexpr unsigned int alignment = DefaultAlignment;
29 
30  static constexpr size_t good_size(size_t n) {
31  return internal::round_to_alignment(alignment, n);
32  }
33 
34 #ifdef _MSC_VER
35  bool aligned_reallocate(block &b, size_t n) noexcept
36  {
37  block reallocatedBlock{ _aligned_realloc(b.ptr, n, alignment), n };
38 
39  if (reallocatedBlock) {
40  b = reallocatedBlock;
41  return true;
42  }
43  return false;
44  }
45 #else
46  // On posix there is no _aligned_realloc so we try a normal realloc
47  // if the result is still aligned we are fine
48  // otherwise we have to do it by hand
49  bool aligned_reallocate(block &b, size_t n) noexcept
50  {
51  block reallocatedBlock(::realloc(b.ptr, n));
52  if (reallocatedBlock) {
53  if (static_cast<size_t>(b.ptr) % alignment != 0) {
54  auto newAlignedBlock = allocate(n);
55  if (!newAlignedBlock) {
56  return false;
57  }
58  internal::block_copy(b, newAlignedBlock);
59  }
60  else {
61  b = reallocatedBlock;
62  }
63 
64  return true;
65  }
66  return false;
67  }
68 #endif
69 
70  public:
71  static constexpr bool supports_truncated_deallocation = false;
77  block allocate(size_t n) noexcept
78  {
79 #ifdef _MSC_VER
80  return block{ _aligned_malloc(n, alignment), n };
81 #else
82  return block{ (void *)memalign(alignment, n), n };
83 #endif
84  }
85 
96  bool reallocate(block &b, size_t n) noexcept
97  {
98  if (internal::is_reallocation_handled_default(*this, b, n)) {
99  return true;
100  }
101 
102  return aligned_reallocate(b, n);
103  }
104 
109  void deallocate(block &b) noexcept
110  {
111  if (b) {
112 #ifdef _MSC_VER
113  _aligned_free(b.ptr);
114 #else
115  ::free(b.ptr);
116 #endif
117  b.reset();
118  }
119  }
120  };
121  }
122  using namespace v_100;
123 }
void reset() noexcept
block allocate(size_t n) noexcept
void block_copy(const block &source, block &destination) noexcept
bool reallocate(block &b, size_t n) noexcept
constexpr size_t round_to_alignment(size_t basis, size_t n) noexcept
void * ptr
This points to the start address of the described memory block.
void deallocate(block &b) noexcept