C++如何简单的实现内存池

来源:互联网 发布:java软件编程培训价格 编辑:程序博客网 时间:2024/05/17 03:57

假如遇到频繁申请释放、频繁释放内存的情况,即使一次申请的内存很少,释放的也很及时,但是我们知道操作系统分配内存并不是连续的,如果频繁申请会在内存中产生许多碎片,因此在程序运行比较长的时间后,占用的内存就会非常大,甚至导致内存不足崩溃。解决办法就是内存池,思想是提前分配一片比较大的连续内存,分配的时候从这片连续内存申请,析构的时候也不释放内存,而是把内存还给内存池。当然内存池也可以扩展,如果内存不足的时候再申请一片更大的内存,有点类似vector的实现,只不过不移位了。boost有memory pool可以实现,单本文介绍的是一种更简洁的实现方式,是通过重载new操作符实现的。代码如下:

#include <stdexcept>


using namespace std;

template <class T> 
class CacheObj
{
public:
void *operator new(std::size_t sz)
{
if(sz != sizeof(T))
throw std::runtime_error("CacheObj: wrong size object in operator new");
if(!freeStore)
{
T* array = alloc_mem.allocate(chunk);
for (size_t i = 0; i != chunk; i++)
add_to_freelist(&array[i]);
}
T* p = freeStore;
freeStore = freeStore->CacheObj<T>::next;
return p;
}
void operator delete(void* p, std::size_t)
{
if(p != 0)
add_to_freelist(static_cast<T*>(p));
}
virtual ~CacheObj(){}


protected:
T* next;


private:
static void add_to_freelist(T* p)
{
p->CacheObj<T>::next = freeStore;
freeStore = p;
}


static std::allocator<T> alloc_mem;
static T* freeStore;
static const std::size_t chunk;
};


template<class T> allocator<T> CacheObj<T>::alloc_mem;
template<class T> T* CacheObj<T>::freeStore = 0;
template<class T> const size_t CacheObj<T>::chunk = 124;

0 0
原创粉丝点击