c++内存池

来源:互联网 发布:炒房洪流中的数据后门 编辑:程序博客网 时间:2024/06/02 07:30

#include<list>

template<class T , int nBlockSize = 512>
class CMemoryPool
{
public:
 CMemoryPool()
 {
  AllocBlock();
 }

 ~CMemoryPool()
 {
  std::list<T*>::iterator it;

  for(it = m_lstLink.begin(); it != m_lstLink.end(); it++)
  {
   T *pBlock = *it;
   
   if(pBlock != NULL)
   {
    delete []pBlock;
    pBlock = NULL;
   }
  }
 }
 
 T* Alloc()
 {
  T *pBuffer = NULL;
  if(m_lstFree.size() == 0)
  {
   AllocBlock();
  }

  pBuffer = m_lstFree.front();
  m_lstFree.pop_front();
 
  return pBuffer;
 }

 void Release(T *pData)
 {
  memset(pData,0,sizeof(T));
  m_lstFree.push_front(pData);
 }
 
private:
 void AllocBlock()
 {
  T *pBlock = new T[nBlockSize];
  m_lstLink.push_back(pBlock);

  for(int i = 0; i < nBlockSize; i++)
  {
   m_lstFree.push_back(pBlock++);
  }
 }

 std::list<T*> m_lstFree;
 std::list<T*> m_lstLink;
};