I want to write a simple space shooter that will be creating and destroying many objects each frame (enemies, bullets, etc.). I don't want to allocate and free memory many times per frame, so I want to use a memory pool. Fortunately boost has one.
I have a couple of questions:
1) I want the syntex to create and destroy objects to be the same whether or not I'm using a memory pool or not, so I created this class:
template <class T>
class PoolObject {
public:
static void* operator new(size_t size) {
return memPool.malloc();
}
static void operator delete(void *p) {
memPool.free(p);
}
private:
static boost::pool<> memPool;
};
template <class T>
boost::pool<> PoolObject<T>::memPool(sizeof(T));
Now, if I want my Bullet class to use pool allocation, I just derive it from this class:
class Bullet : public PoolObject<Bullet> { ... };
void func() {
boost::shared_ptr<Bullet> bullet(new Bullet(...));
b->whatever();
}
My question is, do you see any problems with this or have a better suggestion?
2) When creating a memory pool, you don't specify it's size, so I assume it allocates some fixed amount of memory. But what happens when it runs out of memory? If it will grow the memory like std::vector does, won't that invalidate all the pointers to it?
Thanks in advance.
[Edited by - Gage64 on August 20, 2008 2:48:19 PM]