-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemoryPool.h
More file actions
55 lines (48 loc) · 1.03 KB
/
Copy pathMemoryPool.h
File metadata and controls
55 lines (48 loc) · 1.03 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
#pragma once
#include <cstddef>
#include <utility>
template<typename T, std::size_t capacity>
class MemoryPool
{
public:
MemoryPool()
{
for(std::size_t i = 0; i < capacity; ++i)
{
storage[i].next = data(i + 1);
}
storage[capacity - 1].next = nullptr;
head.next = data(0);
}
[[nodiscard]]T* allocate(T &&inData)
{
if (head.next == nullptr)
{
return nullptr;
}
auto next = head.next->next;
auto d = reinterpret_cast<T*>(head.next);
d = new (d) T(std::move(inData));
head.next = next;
return d;
}
void deallocate(T* x)
{
x->~T();
auto newData = reinterpret_cast<Data*>(x);
newData->next = head.next;
head.next = newData;
}
private:
union Data
{
alignas(T) std::byte data[sizeof(T)];
Data* next;
};
Data storage[capacity];
Data head;
Data* data(const std::size_t i)
{
return &storage[i];
};
};