Pages

23 Apr 2012

auto_ptr concept extended to work with pool of memory.

Based on the concept of Simple auto_ptr implementation, following example shows class reusing allocated heap memory with the aid of a pool.

Features of this implementation are

  • consumers need not worry of destroying memory.
  • Assignment and copy constructor transfer ownership like auto_ptr
  • Destructor doesn't delete allocated memory, instead pushes memory to pool for reuse.
  • static function ClearPool clears memory pool in end.



class MemMgr
{
public:
MemMgr(char* p)
{
if(NULL == memPool.size())
{
//allocate memory only if pool is not having entries
cout<<"Pool size is zero"<<endl;
pMemory = new char[MemSize];

}
else
{
//dont allocate, reuse from pool
cout<<"Pool size is "<<memPool.size()<<endl;
pMemory = memPool.front();
memset(pMemory,0,MemSize);
memPool.pop_front();
}


strncpy((char*)pMemory, p, strlen(p));
((char*)pMemory)[strlen(p)]=0;
}


MemMgr(MemMgr& rhs)
{
//in copy constructor make sure the ownership is transfered
this->pMemory = rhs.pMemory;
rhs.pMemory = NULL;
}


MemMgr& operator =(MemMgr& rhs)
{
if(this->pMemory != rhs.pMemory)
{
//if rhs is different, push lhs to pool
if(NULL != this->pMemory)
{
memPool.push_back(this->pMemory);
this->pMemory = 0;
}
}
//assign rhs memory to lhs
this->pMemory = rhs.pMemory;
//set rhs pointer to null
rhs.pMemory = NULL;
return *this;
}


~MemMgr()
{
if(NULL != this->pMemory)
{
//dont delete memory, push to pool
memPool.push_back(this->pMemory);
this->pMemory = 0;
}
}
void Print()
{
cout<<(char*)pMemory<<endl;
}


//static function to clear pool in end
static void ClearPool()
{
cout<<"Pool size is "<<memPool.size()<<endl;
if(NULL != memPool.size())
{
void* pMem = 0;
for(list<void*>::iterator iter = memPool.begin(); iter != memPool.end(); iter++)
{
delete [] *(iter);
}
}
}


private:
static const int MemSize = 100;
       //our memory pool implemented with stl::list
static list<void*> memPool;
void* pMemory;
};


//don't forget to initialize static member
list<void*> MemMgr::memPool;

No comments:

Post a Comment