C++内存池实现(非线程安全)

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

#pragma once
template<typename T,std::size_t nNum>
class CMemPool
{
public:
 CMemPool(){ Init();}
 ~CMemPool() { Fini();}
 T* GetElement();
 void ReleaseElement(T* t1);
 void Init();
 void Fini();
protected:
 std::list<T*> m_list;
};
template<typename T,std::size_t nNum>
void CMemPool<T,nNum>::Init()
{
 for (size_t i=0; i<nNum; i++)
 {
  T* t1 = new T;
  if (t1 != NULL)
  {
   m_list.push_back(t1);
  }
 }
}
template<typename T,std::size_t nNum>
void CMemPool<T,nNum>::Fini()
{
 std::list<T*>::iterator it = m_list.begin();
 for (; it != m_list.end();)
 {
  T* tTmp = *it;
  it = m_list.erase(it);
  if (tTmp != NULL)
   delete tTmp;
 }
}
template<typename T,std::size_t nNum>
T* CMemPool<T,nNum>::GetElement()
{
 if (m_list.size() == 0)
  Init();
  
 std::list<T*>::iterator it = m_list.begin();
 T* t1 = NULL;
 for(; it != m_list.end();)
 {
  if (*it == NULL)
  {
   it = m_list.erase(it);
  }
  else
  {
   t1 = *it;
   m_list.erase(it);
   break;
  }
 }
 return t1;
}
template<typename T,std::size_t nNum>
void CMemPool<T,nNum>::ReleaseElement(T* t1)
{
 if (t1 != NULL)
  m_list.push_back(t1);
}