-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObjectPool.h
More file actions
109 lines (91 loc) · 2.01 KB
/
Copy pathObjectPool.h
File metadata and controls
109 lines (91 loc) · 2.01 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
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
100
101
102
103
104
105
106
107
108
109
#ifndef OBJECT_POOL_H
#define OBJECT_POOL_H
#include <stack>
#include <vector>
#include "system.h"
namespace game_utils
{
template <class X>
class CObjectPool
{
public:
CObjectPool(bool autoCreateWhenEmpty)
{
this->autoCreateWhenEmpty = autoCreateWhenEmpty;
increaseFactor = 5;
}
~CObjectPool()
{
while (!objects.empty())
{
delete objects.top();
objects.pop();
}
objectList.clear();
}
/*
Creates 'count' objects of same type. This requires a copy
constructor to be implemented for T.
The pool will contain count+1 objects.
*/
void addObjects(X *object, int count, bool addFather=true)
{
if (addFather)
{
objects.push(object);
objectList.push_back(object);
}
for (int i=0; i<count; i++)
{
objects.push(new X(*object));
objectList.push_back(objects.top());
}
}
/*
Whenever we need an object, we call this method.
If there is an object available, we will get it.
If there's none, we get NULL.
*/
X *popObject()
{
if (objects.empty())
{
return NULL;
}
else
{
X *object = objects.top();
objects.pop();
if (objects.size()==1 && autoCreateWhenEmpty)
{
addObjects(object,increaseFactor,false);
}
return object;
}
}
/*
When the object is no more needed, the owner
must return it to the pool.
*/
void pushObject(X *object)
{
objects.push(object);
}
std::vector< X* > *getObjectList()
{
return &objectList;
}
private:
std::stack< X* > objects;
std::vector< X* > objectList; // list of all created resources. just for "safe keeping"
/*
If we're trying to get a resource that has beed depleated,
the pool can automatically create new instances. If this is
se to true, the number of newely create objects will be increased
by increaseFactor.
*/
bool autoCreateWhenEmpty;
int increaseFactor;
};
}
#endif // OBJECT_POOL_H