内存池的C++实现(可能还有小bug)
//pmb_block没走到最后 并且当前block没有可分配结点 { pmb_block=pmb_block->m_pNext;//往后走吧。 } if(pmb_block) //如果找到可分配结点的block { char* pfree=pmb_block->m_data+(pmb_block- >m_nFirst*m_nUnitSize); pmb_block->m_nFirst=*((USHORT*)pfree); pmb_block->m_nFree--;//可分配节点自减 return (void*)pfree; } else//如果找不到,此时pmb_block值为0 { if(m_nGrowSize==NULL) return NULL; pmb_block=new (m_nGrowSize,m_nUnitSize)MemoryBlock (m_nGrowSize,m_nUnitSize); if(!pmb_block) //new不成功 return NULL; pmb_block->m_pNext=m_pFirst;//把新建的block放到最前吧 m_pFirst=pmb_block; return (void*)pmb_block->m_data; } } void MemoryPool::Free(void* pfree) { if(m_pFirst==NULL) return; MemoryBlock* pmb_block=m_pFirst; MemoryBlock* pmb_preblock=m_pFirst; while((ULONG)pfree<(ULONG)pmb_block->m_data|| (ULONG)pfree>(ULONG)(pmb_block->m_data+pmb_block- >m_nSize)) //pfree不在当前block中 { pmb_preblock=pmb_block;//前一个block块 pmb_block=pmb_block->m_pNext; if(!pmb_block) return; } pmb_block->m_nFree++;//可分配数目+1 *((USHORT*)pfree)=pmb_block->m_nFirst; pmb_block->m_nFirst=(USHORT)((ULONG)pfree-(ULONG)pmb_block- >m_data)/m_nUnitSize; if(pmb_block->m_nFree*m_nUnitSize==pmb_block->m_nSize) //如何该链块 为空 { pmb_preblock->m_pNext=pmb_block->m_pNext; if((ULONG)pmb_preblock==(ULONG)m_pFirst) m_pFirst=NULL; delete pmb_block; } } MemoryPool::~MemoryPool(void) { if(m_pFirst) FreeMemoryBlock(m_pFirst); } void MemoryPool::FreeMemoryBlock(MemoryBlock *pblock) { if(pblock->m_pNext) FreeMemoryBlock(pblock->m_pNext); delete pblock; pblock=NULL; } Test.cpp
|
凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢! |