C++内存池的实现

 

#pragma once
#ifndef _MEMORY_POOL_
#define _MEMORY_POOL_
#include <list>
#include <Windows.h>
using std::list;

template <typename Type>
class MemoryPool
{
private:
int m_nMaxCount;
int m_nFreeCount;
list <Type*> 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 <typename Type>
MemoryPool<Type>::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 <typename Type>
inline MemoryPool <Type>::~MemoryPool()
{
delete[] m_pType;
DeleteCriticalSection(&m_csMemLock);
}

template <typename Type>
Type* MemoryPool <Type>::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 <typename Type>
void MemoryPool <Type>::Delete(Type* p)
{
bool bIsValaidPointer = false;
for (int i = 0;i < m_nMaxCount;++i)
{
if (&m_pType[i] == p)
{
//判断p是否是内存池中的内存指针,防止传入其他外部自己new的内存在内部释放
bIsValaidPointer=true;
}
}
list<Type*>::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 <typename Type>
inline int MemoryPool<Type>::GetFreeCount() //获取剩余容量
{
return m_nFreeCount;
}
template <typename Type>
inline bool MemoryPool <Type>::IsFull()
{
return m_nFreeCount == 0?true::false;
}

#endif

你可能感兴趣的:(职场,include,private,public,休闲)