-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathObjectPool.h
85 lines (76 loc) · 1.6 KB
/
ObjectPool.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
//
// ObjectPool.h
// HelloCpp
//
// Created by shaoleibo on 15-2-2.
// Copyright (c) 2015年 Bullets in a Burning Box, Inc. All rights reserved.
//
#ifndef HelloCpp_ObjectPool_h
#define HelloCpp_ObjectPool_h
#include <queue>
#include <vector>
#include <stdexcept>
#include <memory>
using std::queue;
using std::vector;
template <typename T>
class ObjectPool
{
public:
ObjectPool( int chunkSize = 100 );
~ObjectPool();
T& acquireObject();
void releaseObject( T& obj );
protected:
int m_chunkSize;
queue<T*> m_freeList;
vector<T*> m_allObjects;
void allocateChunk();
static void arrayDeleteObject(T* obj);
private:
ObjectPool(const ObjectPool<T>& src);
ObjectPool<T>& operator=(const ObjectPool<T>& rhs);
};
template <typename T>
ObjectPool<T>::ObjectPool( int chunkSize )
{
m_chunkSize = chunkSize;
allocateChunk();
}
template <typename T>
void ObjectPool<T>::allocateChunk()
{
T* newObjects = new T[m_chunkSize];
m_allObjects.push_back( newObjects );
for ( int i = 0; i < m_chunkSize; i++ )
{
m_freeList.push(&newObjects[i]);
}
}
template <typename T>
T& ObjectPool<T>::acquireObject()
{
if ( m_freeList.empty() ) {
allocateChunk();
}
T* obj = m_freeList.front();
m_freeList.pop();
return ( *obj );
}
template <typename T>
void ObjectPool<T>::arrayDeleteObject(T* obj)
{
delete [] obj;
}
template <typename T>
ObjectPool<T>::~ObjectPool()
{
// free each of the allocation chunks
for_each( m_allObjects.begin(), m_allObjects.end(), arrayDeleteObject);
}
template <typename T>
void ObjectPool<T>::releaseObject(T& obj)
{
m_freeList.push( &obj );
}
#endif