-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalign_allocator.hpp
More file actions
76 lines (66 loc) · 1.77 KB
/
align_allocator.hpp
File metadata and controls
76 lines (66 loc) · 1.77 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
64
65
66
67
68
69
70
71
72
73
74
75
76
#pragma once
#include <limits>
#include <memory>
namespace simd {
/**
* @brief 内存对齐分配器
* @ref
* https://github.com/AutoPas/AutoPas/blob/0ea349ddb6c6048e1d00b753864e2c6fedd5b74a/src/autopas/utils/AlignedAllocator.h#L29
* @note 添加了MSVC和其他编译器
*/
template <class T, size_t Alignment>
class AlignedAllocator {
public:
using value_type = T;
using pointer = T*;
using const_pointer = const T*;
using reference = T&;
using const_reference = const T&;
using size_type = size_t;
template <class U>
struct rebind {
using other = AlignedAllocator<U, Alignment>;
};
AlignedAllocator() = default;
template <class U>
AlignedAllocator(const AlignedAllocator<U, Alignment>&) {}
~AlignedAllocator() = default;
size_t max_size() const noexcept {
return (std::numeric_limits<size_t>::max() - size_t(Alignment)) / sizeof(T);
}
T* allocate(std::size_t n) {
void* ptr{nullptr};
size_t size = n * sizeof(T);
#ifdef _MSC_VER
ptr = _aligned_malloc(size, Alignment);
#else
if (posix_memalign(&ptr, Alignment, size) != 0) {
ptr = nullptr;
}
#endif
if (ptr == nullptr) {
throw std::bad_alloc{};
}
return reinterpret_cast<T*>(ptr);
}
void deallocate(T* ptr, std::size_t /*n*/) {
#ifdef _MSC_VER
_aligned_free(ptr);
#else
free(ptr);
#endif
}
template <class U, class... Args>
void construct(U* p, Args&&... args) {
#if __cplusplus > 201703L
std::construct_at(p, std::forward<Args...>(args)...);
#else
::new (static_cast<void*>(p)) U(std::forward<Args...>(args)...);
#endif
}
template <class U>
void destroy(U* p) {
p->~U();
}
};
} // namespace simd