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

58 lines
1.0 KiB
C++
Raw Normal View History

2014-05-21 20:59:04 +01:00
#pragma once
template<class T, size_t BufferSize, class StarvationCallbacks>
class AllocationPool {
public:
~AllocationPool()
{
while (!m_FreeList.empty())
{
delete m_FreeList.front();
m_FreeList.pop_front();
}
}
T* Allocate()
{
if (m_FreeList.Size() <= BufferSize)
{
try
{
return new T;
}
catch (std::bad_alloc& ex)
{
if (m_FreeList.size() == BufferSize)
{
StarvationCallbacks.OnStartingUsingBuffer();
}
else if (m_FreeList.empty())
{
StarvationCallbacks.OnBufferEmpty();
// 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)
{
StarvationCallbacks.OnStopUsingBuffer();
}
2014-05-21 20:59:04 +01:00
}
private:
2014-05-23 15:48:09 +01:00
std::list<void *> m_FreeList;
2014-05-21 20:59:04 +01:00
}