在高效C++编程中看到一个不错的内存池实现方案,这里共享下,大家看看有什么不足。
代码很简单,如下:
template<typename T>
class CMemoryPool
{
public:
enum { EXPANSION_SIZE = 32};
CMemoryPool(unsigned int nItemCount = EXPANSION_SIZE)
{
ExpandFreeList(nItemCount);
}
~CMemoryPool()
{
// free all memory in the list
CMemoryPool<T>* pNext = NULL;
for(pNext = m_pFreeList; pNext != NULL; pNext = m_pFreeList)
{
m_pFreeList = m_pFreeList->m_pFreeList;
delete []( char*)pNext;
}
}
void* Alloc(unsigned int /* size */)
{
if(m_pFreeList == NULL)
{
ExpandFreeList();
}
// get free memory from head
class CMemoryPool
{
public:
enum { EXPANSION_SIZE = 32};
CMemoryPool(unsigned int nItemCount = EXPANSION_SIZE)
{
ExpandFreeList(nItemCount);
}
~CMemoryPool()
{
// free all memory in the list
CMemoryPool<T>* pNext = NULL;
for(pNext = m_pFreeList; pNext != NULL; pNext = m_pFreeList)
{
m_pFreeList = m_pFreeList->m_pFreeList;
delete []( char*)pNext;
}
}
void* Alloc(unsigned int /* size */)
{
if(m_pFreeList == NULL)
{
ExpandFreeList();
}
// get free memory from head