• Announcements

Archived

This topic is now archived and is closed to further replies.

Memory pools - How do people use them usually?

Recommended Posts

civguy    308
I couldn''t think of any proper use for boost''s memory pools until I wrote the following template class. It overrides new and delete and can be used with any class.

#include <boost/pool/pool.hpp>

template <class T>
class ObjectAllocator {
public:
static void* operator new(size_t size) {
if (size != sizeof(T))
return ::operator new(size);
return memPool.malloc();
}

static void operator delete(void* p, size_t size) {
if (size != sizeof(T)) {
::operator delete(p);
return;
}
memPool.free(p);
}

private:
static boost::pool<> memPool;
};

template <class T>
boost::pool<> ObjectAllocator<T>::memPool(sizeof(T));

Usage:

//old class (slow new/delete):

class A {
public:
int field1;
int field2;
};

//new class (fast new/delete):

class A : public ObjectAllocator<A> {
public:
int field1;
int field2;
};

No changes need to be done anywhere else, and it has 10 times faster new/delete than the basic version. It should also work with derived types, because it checks that the object size is correct (I haven''t done much testing yet) Now the question is.. How come none of the boost''s ready-made pools did this? And why haven''t I seen this technique used anywhere, even though it should be used everywhere :D (ok, it''s not like I look a lot on other people''s source code)? I.e. there must be something wrong with it And how do you use memory pools?

Share on other sites
Guest Anonymous Poster
The only problem I can see is when multiple threads try to allocate an object of the same type which uses your memory allocation mechanism. Other than that I think it is a very good idea and I intend on using it.