blob: b3818e8b1a81fb901ad56d2308818834a929aafe (
plain) (
blame)
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
|
#pragma once
#include <memory>
template<class T, size_t BufferSize>
class cAllocationPool {
public:
class cStarvationCallbacks
{
public:
virtual ~cStarvationCallbacks() {}
virtual void OnStartingUsingBuffer() = 0;
virtual void OnStopUsingBuffer() = 0;
virtual void OnBufferEmpty() = 0;
};
cAllocationPool(std::auto_ptr<cStarvationCallbacks> a_Callbacks) :
m_Callbacks(a_Callbacks)
{
}
~cAllocationPool()
{
while (!m_FreeList.empty())
{
free (m_FreeList.front());
m_FreeList.pop_front();
}
}
T* Allocate()
{
if (m_FreeList.size() <= BufferSize)
{
try
{
return new(malloc(sizeof(T))) T;
}
catch (std::bad_alloc&)
{
if (m_FreeList.size() == BufferSize)
{
m_Callbacks->OnStartingUsingBuffer();
}
else if (m_FreeList.empty())
{
m_Callbacks->OnBufferEmpty();
// Try again until the memory is avalable
return Allocate();
}
}
}
// placement new, used to initalize the object
T* ret = new (m_FreeList.front()) T;
m_FreeList.pop_front();
return ret;
}
void Free(T* ptr)
{
// placement destruct.
ptr->~T();
m_FreeList.push_front(ptr);
if (m_FreeList.size() == BufferSize)
{
m_Callbacks->OnStopUsingBuffer();
}
}
private:
std::list<void *> m_FreeList;
std::auto_ptr<cStarvationCallbacks> m_Callbacks;
};
|