一个简单C\C++内存池,网址如下:http://www.codeproject.com/Articles/27487/Why-to-use-memory-pool-and-how-to-implement-it,大体思路为:初始化时,分配几十个固定大小的内存块供程序使用,程序需要内存时,直接从内存池中取,释放内存时,内存池回收。该程序的内存分配时这样的,不管分配多大内存,只要内存池中有内存块并且内存块大小大于所需要分配的内存,就把这个内存块分配给程序使用,但是这个内存块剩下的内存就不能用了,所以这个内存池实现起来非常简单。共包含两个文件,一个头文件和一个cpp文件。
MemPool.h文件:
class CMemPool { private: struct _Unit //链表结点 { struct _Unit *pPrev, *pNext; }; void* m_pMemBlock; //内存池的首地址 struct _Unit* m_pAllocatedMemBlock; //指向已分配出去的内存结点 struct _Unit* m_pFreeMemBlock; //指向未分配出去的内存结点 unsigned long m_ulUnitSize; //内存单元个数 unsigned long m_ulBlockSize; //内存单元大小 public: CMemPool(unsigned long lUnitNum = 50, unsigned long lUnitSize = 1024); ~CMemPool(); void* Alloc(unsigned long ulSize, bool bUseMemPool = true); //分配内存 void Free( void* p ); //释放内存 };
MemPool.cpp文件:
CMemPool::CMemPool(unsigned long ulUnitNum,unsigned long ulUnitSize) : m_pMemBlock(NULL), m_pAllocatedMemBlock(NULL), m_pFreeMemBlock(NULL), m_ulBlockSize(ulUnitNum * (ulUnitSize+sizeof(struct _Unit))), m_ulUnitSize(ulUnitSize) { m_pMemBlock = ::malloc(m_ulBlockSize); //申请内存 if(NULL != m_pMemBlock) { for(unsigned long i=0; i<ulUnitNum; i++) //将所有内存结点链接起来 { struct _Unit *pCurUnit = (struct _Unit *)( (char *)m_pMemBlock + i*(ulUnitSize+sizeof(struct _Unit)) ); pCurUnit->pPrev = NULL; pCurUnit->pNext = m_pFreeMemBlock; if(NULL != m_pFreeMemBlock) { m_pFreeMemBlock->pPrev = pCurUnit; } m_pFreeMemBlock = pCurUnit; } } } CMemPool::~CMemPool() { ::free(m_pMemBlock); } void* CMemPool::Alloc(unsigned long ulSize, bool bUseMemPool) { if(ulSize > m_ulUnitSize || false == bUseMemPool || NULL == m_pMemBlock || NULL == m_pFreeMemBlock) { return malloc(ulSize); } struct _Unit *pCurUnit = m_pFreeMemBlock; m_pFreeMemBlock = pCurUnit->pNext; //从空闲链表中取出一个内存单元,放入已分配链表中,并返回该单元的内存地址 if(NULL != m_pFreeMemBlock) { m_pFreeMemBlock->pPrev = NULL; } pCurUnit->pNext = m_pAllocatedMemBlock; if(NULL != m_pAllocatedMemBlock) { m_pAllocatedMemBlock->pPrev = pCurUnit; } m_pAllocatedMemBlock = pCurUnit; return (void *)((char *)pCurUnit + sizeof(struct _Unit) ); } void CMemPool::Free( void* p ) { if(m_pMemBlock<p && p<(void *)((char *)m_pMemBlock + m_ulBlockSize) ) { struct _Unit *pCurUnit = (struct _Unit *)((char *)p - sizeof(struct _Unit) ); m_pAllocatedMemBlock = pCurUnit->pNext; //从已分配链表取出回收的内存单元,放入空闲链表中 if(NULL != m_pAllocatedMemBlock) { m_pAllocatedMemBlock->pPrev = NULL; } pCurUnit->pNext = m_pFreeMemBlock; if(NULL != m_pFreeMemBlock) { m_pFreeMemBlock->pPrev = pCurUnit; } m_pFreeMemBlock = pCurUnit; } else { free(p); }