-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaligned_allocator.h
More file actions
63 lines (52 loc) · 2.27 KB
/
aligned_allocator.h
File metadata and controls
63 lines (52 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#ifndef ALIGNED_ALLOCATOR_H
#define ALIGNED_ALLOCATOR_H
#include <memory>
#include <stdlib.h>
// A minimal implementation of an allocator for C++ Standard Library, which
// allocates aligned memory (specified by the alignment argument).
// Note:
// A minimal custom allocator is preferred because C++ allocator_traits class
// provides default implementation for you. Take a look at Microsoft's
// documentation about Allocators and allocator class.
template <typename T, std::size_t alignment> class AlignedAllocator {
public:
using value_type = T;
public:
// According to Microsoft's documentation, default constructor is not required
// by C++ Standard Library.
AlignedAllocator() noexcept {};
template <typename U> AlignedAllocator(const AlignedAllocator<U, alignment>& other) noexcept {};
template <typename U>
inline bool operator==(const AlignedAllocator<U, alignment>& other) const noexcept {
return true;
}
template <typename U>
inline bool operator!=(const AlignedAllocator<U, alignment>& other) const noexcept {
return false;
}
template <typename U> struct rebind {
using other = AlignedAllocator<U, alignment>;
};
// STL containers call this function to allocate uninitialized memory block to
// store (no more than n) elements of type T (value_type).
inline value_type* allocate(const std::size_t n) const {
auto size = n;
/*
If you wish, for some strange reason, that the size of allocated buffer is
also aligned to alignment, uncomment the following statement.
Note: this increases the size of underlying memory, but STL containers
still treat it as a memory block of size n, i.e., STL containers will not
put more than n elements into the returned memory.
*/
// size = (n + alignment - 1) / alignment * alignment;
value_type* ptr;
auto ret = posix_memalign((void**)&ptr, alignment, sizeof(T) * size);
if (ret != 0)
throw std::bad_alloc();
return ptr;
};
// STL containers call this function to free a memory block beginning at a
// specified position.
inline void deallocate(value_type* const ptr, std::size_t n) const noexcept { free(ptr); }
};
#endif