Brian Clifton . com

Simple object pool in C++

Posted by Brian Clifton
Written November 26, 2009 at 02:52
This is a simple object pool I use in my C++ code. It provides good performance and avoids memory fragmentation. I based the code on an example from Game Programming Gems 4.
#include <stdlib.h>
#include <list>

using namespace std;

class TestObject{
    public:
        int _TestValue;
        TestObject(void)
        {
            _TestValue = 0;
        }
};

template<class OPDataType> class ObjectPool{
    protected:
        OPDataType* _ObjectData;
        OPDataType** _ObjectFree;
        int _ObjectCount,_Top;

    protected:
        void FreeAll(void)
        {
            int i = (_ObjectCount-1);

            for(_Top=0;_Top<_ObjectCount;_Top++){
                _ObjectFree[_Top] = &_ObjectData[i--];
            }
            return;
        }
    public:
        void FreeInstance(OPDataType* instance)
        {
            if((instance) && (_Top<_ObjectCount) && (instance>=&_ObjectData[0]) && (instance<=&_ObjectData[_ObjectCount-1])){
                _ObjectFree[_Top++] = instance;
            }
            return;
        }

        OPDataType* NewInstance(void)
        {
            if(_Top>0){
                return(_ObjectFree[--_Top]);
            }
            return(0);
        }

        ObjectPool(int count)
        {
            _ObjectData = new OPDataType[count];
            _ObjectFree = new OPDataType*[count];

            _ObjectCount = count;

            FreeAll();
        }

        virtual ~ObjectPool(void)
        {
            delete[] _ObjectData;
            delete[] _ObjectFree;
        }
};

#define TEST_POOL_SIZE 200

int main(int argc,char** argv)
{
    ObjectPool<TestObject> pool(TEST_POOL_SIZE);
    list<TestObject*> objects;

    for(int i=0;i<TEST_POOL_SIZE;i++){
        TestObject* test = pool.NewInstance();
        test->_TestValue = rand();
        objects.push_back(test);
    }

    list<TestObject*>::iterator it = objects.begin();
    while(it != objects.end()){
        pool.FreeInstance( (*it) );
        ++it;
    }

    objects.clear();

    return(0);
}

 

© Brian Clifton. All rights reserved.