Question

So I was working on a way to memory pool c++ objects easily with minimal modification needed to the class that needs to be pooled.

The memory pool itself is the standard variety you can find anywhere, but I've made this class:

  Poolable::Poolable(MemPool& lepool){
     mempool = &lepool;
  }

  Poolable::~Poolable(){
     mempool->returnMemory((char*)this);
  }

  void * Poolable::operator new(size_t size, MemPool& lepool){
     if(!lepool.initialised())
        lepool.initializeBasedOnSize(size);

     return lepool.getMemory(size);

  }

  void Poolable::operator delete(void * p){
     // do absolutely NOTHING
  }

usage:

  class SomeSubclass : public Poolable { /* boring details here */ };
  MemPool thepool(1000);
  SomeSubclass * woot = new(thepool) SomeSubclass(thepool);

I wanted to put the returnMemory call (which basically frees a part of the pool) in the delete operator, but have no idea how to get the actual pool's address from the void* argument.

Instead, I settled by putting it in the destructor. I figure that the constructor mandates that the class was allocated using the pool, which means destruction always implies unallocation will follow.

It's the first working solution, and it's quite convenient to use. However, doing that is probably bad style, and I'm curious if there are better solutions to the problem.

Does anybody know of one?

Was it helpful?

Solution

An alternative would be to make Poolable::operator new allocate memory from thepool so that you can use usual (non-placement) new statements. In your solution the user has to remember that those objects are to be allocated via some special technique, that's showing too much details and putting too much burden onto the user code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top