这是可以时常切换的MemoryPool
#ifndef MEMORY_POOL
#define MEMORY_POOL
template<typename Ty>
class GD_MemoryPool
{
public:
enum{m_nBlock = 32};
GD_MemoryPool(size_t nBlock = m_nBlock)
{
m_Expand(nBlock);
}
~GD_MemoryPool()
{
if(pListMemoryPool != null)
{
GD_MemoryPool<Ty>* pList = pListMemoryPool;
while(pListMemoryPool)
{
pList = pListMemoryPool->pListMemoryPool;
delete []static_cast<byte*>(pList);
pListMemoryPool = pList;
}
}
}
void m_FreeMemory(void* pBlock)
{
if(pBlock != null)
{
GD_MemoryPool<Ty>* pRelease = static_cast<GD_MemoryPool<Ty>*>(pBlock);
pRelease->pListMemoryPool = pListMemoryPool;
pListMemoryPool = pRelease;
}
}
void* m_Allocator()
{
GD_MemoryPool<Ty>* pList = nullptr;
if(pListMemoryPool == null)
{
pList = m_Expand(m_nBlock);
}
pList = pListMemoryPool->pListMemoryPool;
return pList;
}
void* m_Allocator()
{
GD_MemoryPool<Ty>* pList = nullptr;
if(pListMemoryPool == null)
{
pList = m_Expand(m_nBlock);
}
pList = pListMemoryPool->pListMemoryPool;
return pList;
}
protected:
void* m_Expand(size_t nCount)
{
//size_t MaxByte to get sizeof(Ty)
size_t maxByte = sizeof(GD_MemoryPool<Ty*>);
GD_MemoryPool<Ty>* pPreList = static_cast<GD_MemoryPool<Ty>*>(static_cast<void*>(byte[maxByte]));
pListMemoryPool = pPreList;
GD_MemoryPool<Ty>* pPostList = nullptr;
for(size_t i = 0;i < nCount; ++i)
{
pPostList = static_cast<GD_MemoryPool<Ty>*>(static_cast<void*>(byte[maxByte]));
pPreList->PListMemoryPool = pPostList;
pPreList = pPostList;
}
}
private:GD_MemoryPool<Ty>* pListMemoryPool;
};
原理是:利用一个List把所有的Memory链接在一起;然后如果释放完一个Memory把它放在头结点的位置,然后每次去Memory都从头结点取;
的一个内存池就可以循环使用;
希望各位批评指正,我的程序是存在在单线程;然后但是还是没有特别好的管理内存