#pragma once
#ifndef _MEMORY_POOL_
#define _MEMORY_POOL_
#include
#include
using std::list;

template
class MemoryPool
{
private:
int m_nMaxCount;
int m_nFreeCount;
list m_pMemList;
Type * m_pType;
CRITICAL_SECTION m_csMemLock;
public:
MemoryPool(int nMax);
~MemoryPool();
Type* New();
void Delete(Type* p);
int GetFreeCount();
bool IsFull();
};
template
MemoryPool::MemoryPool(int nMax)
{
m_pType=NULL;
m_pType=new (std::nothrow) Type[nMax];
if (m_pType!=NULL)
{
for (int i = 0; i < nMax; ++i)
{
m_pMemList.push_back(&m_pType[i]);
}
m_nMaxCount=nMax;
m_nFreeCount=m_nMaxCount;
}
else
{
m_nMaxCount=0;
m_nFreeCount=0;
}
InitializeCriticalSection(&m_csMemLock);
}

template
inline MemoryPool ::~MemoryPool()
{
delete[] m_pType;
DeleteCriticalSection(&m_csMemLock);
}

template
Type* MemoryPool ::New()
{

Type* pNew=NULL;
if (m_pType != NULL && m_nFreeCount > 0)
{
EnterCriticalSection(&m_csMemLock);
pNew=m_pMemList.front();
m_pMemList.pop_front();
LeaveCriticalSection(&m_csMemLock);
--m_nFreeCount;
}
return pNew;
}

template
void MemoryPool ::Delete(Type* p)
{
bool bIsValaidPointer = false;
for (int i = 0;i < m_nMaxCount;++i)
{
if (&m_pType[i] == p)
{
//判断p是否是内存池中的内存指针,防止传入其他外部自己new的内存在内部释放
bIsValaidPointer=true;
}
}
list::iterator iter;
for (iter = m_pMemList.begin();iter != m_pMemList.end();++iter)
{
if (*iter==p)
{
//判断p是否已经被释放过了,防止对同一指针多次释放
bIsValaidPointer = false;
}
}
if (p != NULL && m_pType != NULL && m_nFreeCount < m_nMaxCount && bIsValaidPointer)
{
EnterCriticalSection(&m_csMemLock);
m_pMemList.push_front(p);
LeaveCriticalSection(&m_csMemLock);
++m_nFreeCount;
}
}
template
inline int MemoryPool::GetFreeCount() //获取剩余容量
{
return m_nFreeCount;
}
template
inline bool MemoryPool ::IsFull()
{
return m_nFreeCount == 0?true::false;
}

#endif