-
Notifications
You must be signed in to change notification settings - Fork 1
/
AlignedAllocator.h
72 lines (61 loc) · 1.7 KB
/
AlignedAllocator.h
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
#include <malloc.h>
#include <memory>
template <class T, size_t Alignment>
struct AlignedAllocator : public std::allocator<T>
{
typedef typename std::allocator<T>::size_type size_type;
typedef typename std::allocator<T>::pointer pointer;
typedef typename std::allocator<T>::const_pointer const_pointer;
template <class U>
struct rebind
{
typedef AlignedAllocator<U, Alignment> other;
};
AlignedAllocator() throw() { }
AlignedAllocator(const AlignedAllocator &other) throw()
: std::allocator<T>(other)
{
}
template <class U>
AlignedAllocator(const AlignedAllocator<U, Alignment> &) throw()
{
}
~AlignedAllocator() throw()
{
}
template <class T1, size_t A1>
bool operator==(const AlignedAllocator<T1,A1> &) const
{
return true;
}
template <class T1, size_t A1>
bool operator!=(const AlignedAllocator<T1,A1> &) const
{
return false;
}
pointer allocate(size_type n)
{
return allocate(n, const_pointer(0));
}
pointer allocate(size_type n, const_pointer /*hint*/)
{
void *ptr;
#ifdef _WIN32
ptr = _aligned_malloc(n*sizeof(T), Alignment);
#else
if (posix_memalign(&ptr, Alignment, n*sizeof(T)))
ptr = NULL;
#endif
if (!ptr)
throw std::bad_alloc();
return static_cast<pointer>(ptr);
}
void deallocate(pointer p, size_type /*n*/)
{
#ifdef _WIN32
_aligned_free(p);
#else
free(p);
#endif
}
};