Generic Memory Pool - How to? - Design Issue

爱⌒轻易说出口 提交于 2019-12-11 02:25:09

问题


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.

来源:https://stackoverflow.com/questions/27375620/generic-memory-pool-how-to-design-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!