-
Notifications
You must be signed in to change notification settings - Fork 5
/
Pool.h
99 lines (80 loc) · 2.06 KB
/
Pool.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//
// Pool.h
//
// This code is derived from Universal Tween Engine
// Licensed under Apache License 2.0 - http://www.apache.org/licenses/LICENSE-2.0
//
/**
* A light pool of objects that can be resused to avoid allocation.
* Based on Nathan Sweet pool implementation
*/
#ifndef __Pool__
#define __Pool__
#include <vector>
namespace TweenEngine
{
template<typename T>
class PoolCallback
{
public:
virtual void onPool(T *obj) = 0;
virtual void onUnPool(T *obj) = 0;
};
template<typename T>
class Pool
{
private:
std::vector<T *> objects;
PoolCallback<T> *callback;
protected:
virtual ~Pool() {}
virtual T *create()=0;
public:
Pool(int initCapacity, PoolCallback<T> *callback);
T *get();
void free(T *obj);
void clear();
size_t size();
void ensureCapacity(int minCapacity);
};
// Implementation
template <typename T>
Pool<T>::Pool(int initCapacity, PoolCallback<T> *cb) : objects(initCapacity), callback(cb)
{
}
template <typename T>
T *Pool<T>::get()
{
T *obj = NULL;
if (objects.empty())
{
obj = create();
}
else
{
obj = objects.back();
objects.pop_back();
if (obj == NULL) obj = create();
}
if (callback != NULL) callback->onUnPool(obj);
return obj;
}
template <typename T>
void Pool<T>::free(T *obj)
{
if (obj == NULL) return;
bool contains = (std::find(objects.begin(), objects.end(), obj) != objects.end());
if (!contains)
{
if (callback != NULL) callback->onPool(obj);
objects.push_back(obj);
}
}
template <typename T>
void Pool<T>::clear() { objects.clear(); }
template <typename T>
size_t Pool<T>::size() { return objects.size(); }
template <typename T>
void Pool<T>::ensureCapacity(int minCapacity) { objects.reserve(minCapacity); }
}
#endif /* defined(__Pool__) */