-
Notifications
You must be signed in to change notification settings - Fork 1
/
aligned_allocator.hpp
48 lines (40 loc) · 1.08 KB
/
aligned_allocator.hpp
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
#ifndef ALIGNED_ALLOCATOR_HPP_
#define ALIGNED_ALLOCATOR_HPP_
#include <malloc.h>
#include <new>
#include <stdexcept>
#include <sstream>
template<typename T, size_t Align = 16>
class aligned_allocator {
public:
using value_type = T;
aligned_allocator() noexcept = default;
aligned_allocator(const aligned_allocator&) noexcept = default;
~aligned_allocator() noexcept = default;
template<typename U>
struct rebind {
typedef aligned_allocator other;
};
T* allocate(size_t n) {
T *data = static_cast<T*>(aligned_alloc(Align, n * sizeof(T)));
if (!data) {
std::stringstream ss;
ss << "Unable to allocate " << n * sizeof(T) / 1024.0f << " MB of memory.\n";
throw std::runtime_error { ss.str() };
}
return data;
}
void deallocate(T *p, __attribute__((unused)) size_t n) {
if (p)
free(p);
}
};
template<class T, class U>
bool operator==(const aligned_allocator<T>&a, const aligned_allocator<U>&b) noexcept {
return false;
}
template<class T, class U>
bool operator !=(const aligned_allocator<T>&a, const aligned_allocator<U>&b) noexcept {
return !(a == b);
}
#endif