forked from ideawu/icomet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobjpool.h
More file actions
52 lines (45 loc) · 784 Bytes
/
objpool.h
File metadata and controls
52 lines (45 loc) · 784 Bytes
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
#ifndef UTIL_OBJPOOL_H
#define UTIL_OBJPOOL_H
#include <list>
#include <vector>
template <class T>
class ObjPool{
private:
int size;
std::vector<T *> chunks;
std::list<T *> pool;
public:
ObjPool(int init_size = 4){
if(init_size <= 0){
init_size = 1;
}
this->size = init_size;
pre_alloc(this->size);
}
void pre_alloc(int new_size){
T *chunk = new T[new_size];
chunks.push_back(chunk);
for(int i=0; i<new_size; i++){
T *t = &chunk[i];
pool.push_back(t);
}
this->size += new_size;
}
~ObjPool(){
for(int i=0; i<chunks.size(); i++){
delete[] chunks[i];
}
}
T* alloc(){
if(pool.empty()){
pre_alloc(this->size * 2);
}
T *t = pool.front();
pool.pop_front();
return t;
}
void free(T *t){
pool.push_front(t);
}
};
#endif