I am creating my own memory pool for small and very frequently used objects. I am good with the allocation and d-allocation itself.
Here is layout of my Pool
class CPool
{
unsigned int m_uiBlocks;
unsigned int m_uiSizeOfBlock;
unsigned int m_uiFreeBlocks;
unsigned int m_uiInitialized;
unsigned char *m_pMemStart;
unsigned char *m_pNext;
public:
CPool();
~CPool();
void CreatePool(size_t sizeOfEachBlock, unsigned int numOfBlocks);
void DestroyPool();
unsigned char* AddrFromIndex(unsigned int i) const;
unsigned int IndexFromAddr(const unsigned char* p) const;
void* Allocate();
void DeAllocate(void* p);
};
I would want each class to have its own pool. Now, if some class needs to use this pool, it is needed that
- They call
CreatePool()
with size and no_of_objects - They either call parameterised
new
&delete
or overload operators and callAllocate
andDeAllocate
functions from those. - call 'DestroyPool()'
I am more worried about calls like Derived *derObj = new (poolObj)Derived();
. Here user may forget poolObj
and that object will not be on my heap at all. Of course, for this to work I have global function like
inline void* operator new(size_t size, CPool& objPool)
{
return objPool.Allocate();
}
So I would want to ask specific questions:
How do I re-design my pool class so that if client calls
Derived *derObj = new Derived();
I have a chance to allocate memory from my pool. Is it even possible?Is there way to recognize
type
of object? So thatCreatePool
andDestroyPool
can also be removed from client code? But I would need to be very careful that there is only one pool per 'type'.
I am ready to use templated code as well, but I am not sure what to templatize. Please suggest.