-
Notifications
You must be signed in to change notification settings - Fork 0
/
instance_pool.hpp
76 lines (67 loc) · 1.56 KB
/
instance_pool.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
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 "memory_pool.hpp"
#include <list>
template <class T>
class InstancePool
{
public:
typedef T *pointer_type;
~InstancePool()
{
for (auto ptr: pointers_) {
ptr->~T();
pool_.Deallocate(ptr);
}
}
pointer_type Construct()
{
auto ptr = pool_.Allocate();
if (ptr != NULL) {
new (ptr) T();
pointers_.push_back(static_cast<pointer_type>(ptr));
}
return static_cast<pointer_type>(ptr);
}
template <class A0>
pointer_type Construct(const A0 &a0)
{
auto ptr = pool_.Allocate();
if (ptr != NULL) {
new (ptr) T(a0);
pointers_.push_back(static_cast<pointer_type>(ptr));
}
return static_cast<pointer_type>(ptr);
}
template <class A0, class A1>
pointer_type Construct(const A0 &a0, const A1 &a1)
{
auto ptr = pool_.Allocate();
if (ptr != NULL) {
new (ptr) T(a0, a1);
pointers_.push_back(static_cast<pointer_type>(ptr));
}
return static_cast<pointer_type>(ptr);
}
template <class A0, class A1, class A2>
pointer_type Construct(const A0 &a0, const A1 &a1, const A2 &a2)
{
auto ptr = pool_.Allocate();
if (ptr != NULL) {
new (ptr) T(a0, a1, a2);
pointers_.push_back(static_cast<pointer_type>(ptr));
}
return static_cast<pointer_type>(ptr);
}
void Destroy(pointer_type ptr)
{
if (ptr != NULL) {
ptr->~T();
pointers_.remove(ptr);
pool_.Deallocate(ptr);
printf("count = %zu\n", pointers_.size());
}
}
private:
MemoryPool<sizeof (T)> pool_;
std::list<pointer_type> pointers_;
};