这是我写的一个简单的内存管理类,主要是用在:如果有种大小不变的对象要频繁的new和delete,为了防止产生大量的内存碎片和提高效率,可以考虑使用下面的内存管理类。下一篇文章,我将介绍如何使用这个类
#ifndef _MEMPOOL_H
#define _MEMPOOL_H
/********************************************************************
created: 2004/11/29
created: 29:11:2004 16:02
filename: ..\memory pool\test\cmempool.h
file path: ..\memory pool\test
file base: cmempool
file ext: h
author: David
purpose: 同等大小的小对象如果频繁的动态申请与释放(eg: s
erver),必然会导致系统产生大量的内存碎片,这样
当系统长时间的运行后,就会因为大量的内存碎片而
导致无法再分配出内存,这样我们的软件就会变的不
稳定,而且频繁的new和delete会导致效率低下,因此
需要有自己内存管理。下面的类就是一个简单的内存
管理。
*********************************************************************/
#include "Lock.h"
template <class CNode>
struct Mem_Pool_Node
{
union {
char Obj[sizeof(CNode)];
Mem_Pool_Node *m_pNext;
};
};
template <class CNode>
class CMemPool
{
typedef Mem_Pool_Node<CNode>* Mem_Pool_Node_Type;
public:
CMemPool(){
m_pListFreePool = NULL;
m_nInuse = 0;
m_nFree = 0;
};
virtual ~CMemPool(){
Mem_Pool_Node_Type pPreNode= NULL;
Mem_Pool_Node_Type pNode= NULL;
m_Lock.Lock();
pPreNode = m_pListFreePool;
pNode = m_pListFreePool;
while (NULL != pNode) {
pPreNode = pNode;
pNode = pNode->m_pNext;
delete pPreNode;
pPreNode = NULL;
}
m_Lock.Unlock();
};
CNode *Allocate(){
void *p = NULL;
Mem_Pool_Node_Type pNode= NULL;
if (NULL == m_pListFreePool) {
try{
p = (::operator new(sizeof(CNode)));
}
catch (...) {
if (p != NULL) {
::operator delete ((CNode *)(p));
p = NULL;
}
return NULL;
}
m_Lock.Lock();
m_nInuse++;
m_Lock.Unlock();
}
else{
m_Lock.Lock();
pNode = m_pListFreePool;
m_pListFreePool = m_pListFreePool->m_pNext;
p = pNode;
m_nFree--;
m_nInuse++;
m_Lock.Unlock();
}
return static_cast<CNode *>(p);
};
void Release(void *p){
if (NULL == p) {
return;
}
m_Lock.Lock();
if (NULL == m_pListFreePool) {
m_pListFreePool = static_cast<Mem_Pool_Node_Type>(p);
m_pListFreePool->m_pNext = NULL;
}
else{
(static_cast<Mem_Pool_Node_Type>(p))->m_pNext = m_pListFreePool;
m_pListFreePool = static_cast<Mem_Pool_Node_Type>(p);
}
m_nInuse--;
m_nFree++;
m_Lock.Unlock();
};
void GetInfo(int &inuse, int &free){
inuse = m_nInuse;
free = m_nFree;
};
private:
CLock m_Lock;
int m_nInuse;
int m_nFree;
Mem_Pool_Node_Type m_pListFreePool;
};
#endif
本文地址:http://com.8s8s.com/it/it24933.htm