Generic Memory Pool - How to? - Design Issue

436 views Asked by At

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

  1. They call CreatePool() with size and no_of_objects
  2. They either call parameterised new & delete or overload operators and call Allocate and DeAllocate functions from those.
  3. 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:

  1. 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?

  2. Is there way to recognize type of object? So that CreatePool and DestroyPool 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.

0

There are 0 answers