I have been looking at memory pools and was wondering what would be wrong with creating a singleton which create a "pool" of (allocated) pointers to a given struct/class( in the case below Messages ), and then when a client needs a "new" one pass them one from your free message queue. Any thoughts, potential problems, etc, would be appreciated. Thanks.
Code:
class MsgPool
{
public:
~MsgPool();
static void recycleMem(Message* msg);
static Message* newMessage();
static MsgPool* createInstance();
private:
MsgPool();
static MsgPool* msgPoolInstance;
static Message* msgPtr;
static std::queue<Message*> msgPtrPool;
};
MsgPool* MsgPool::msgPoolInstance = NULL;
std::queue<Message*> MsgPool::msgPtrPool;
Message* MsgPool::msgPtr;
//CCONSTRUCTOR/DESTRUCTORS
//----------------------------------------------------------------------------------------------//
MsgPool::MsgPool()
{
while (msgPtrPool.size() < INITPTRPOOL) {
msgPtr = new Message();
msgPtrPool.push(msgPtr);
}
}
MsgPool::~MsgPool()
{
if (msgPoolInstance != NULL) {
while (!msgPtrPool.empty()) {
msgPtr = msgPtrPool.front();
msgPtrPool.pop();
delete msgPtr;
}
delete msgPoolInstance;
msgPoolInstance = NULL;
}
}
//----------------------------------------------------------------------------------------------//
//INSTANCE CREATION
//----------------------------------------------------------------------------------------------//
//This function creates the one and only instance of the message pool
MsgPool* MsgPool::createInstance()
{
if (msgPoolInstance == NULL) {
msgPoolInstance = new MsgPool();
}
return msgPoolInstance;
}
//----------------------------------------------------------------------------------------------//
//"ALLOCATION/DEALLOCATION"
//----------------------------------------------------------------------------------------------//
//This function puts a given pointer back into the pool
void MsgPool::recycleMem(Message* msg)
{
if (msg != NULL) {
msgPtrPool.push(msg);
}
else
std::cerr <<"Passed NULL ptr" << std::endl;
}
//This function returns a message pointer
Message* MsgPool::newMessage()
{
//If out of memory in pool allocate new memory
if (msgPtrPool.empty()) {
return (new Message);
}
else
{
msgPtr = msgPtrPool.front();
msgPtrPool.pop();
return msgPtr;
}
}
Comment