Files
cuberite-2a/src/AllocationPool.h
T

75 lines
1.4 KiB
C++
Raw Normal View History

2014-05-21 20:59:04 +01:00
#pragma once
#include <memory>
template<class T, size_t BufferSize>
class cAllocationPool {
2014-05-21 20:59:04 +01:00
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)
{
}
2014-05-21 20:59:04 +01:00
~cAllocationPool()
2014-05-21 20:59:04 +01:00
{
while (!m_FreeList.empty())
{
free (m_FreeList.front());
2014-05-21 20:59:04 +01:00
m_FreeList.pop_front();
}
}
T* Allocate()
{
if (m_FreeList.size() <= BufferSize)
2014-05-21 20:59:04 +01:00
{
try
{
return new(malloc(sizeof(T))) T;
2014-05-21 20:59:04 +01:00
}
catch (std::bad_alloc&)
2014-05-21 20:59:04 +01:00
{
if (m_FreeList.size() == BufferSize)
{
m_Callbacks->OnStartingUsingBuffer();
2014-05-21 20:59:04 +01:00
}
else if (m_FreeList.empty())
{
m_Callbacks->OnBufferEmpty();
2014-05-21 20:59:04 +01:00
// Try again until the memory is avalable
return Allocate();
}
}
}
2014-05-23 15:48:09 +01:00
// placement new, used to initalize the object
T* ret = new (m_FreeList.front()) T;
2014-05-21 20:59:04 +01:00
m_FreeList.pop_front();
return ret;
}
void Free(T* ptr)
{
2014-05-23 15:48:09 +01:00
// placement destruct.
ptr->~T();
2014-05-21 20:59:04 +01:00
m_FreeList.push_front(ptr);
2014-05-21 21:30:08 +01:00
if (m_FreeList.size() == BufferSize)
{
m_Callbacks->OnStopUsingBuffer();
2014-05-21 21:30:08 +01:00
}
2014-05-21 20:59:04 +01:00
}
private:
2014-05-23 15:48:09 +01:00
std::list<void *> m_FreeList;
std::auto_ptr<cStarvationCallbacks> m_Callbacks;
};