How to write an generic object pool in c++

910 views Asked by At

I want to write an generic object pool class and the object pool should be singleton, it is easy to access that object pool everywhere.

template <class T>
class Pool
{
    T* _freeObjs;
 public:
    Pool<T>& getInstance()
    {
        static Pool<T> instance;
        return instance;
    }
    
    T* acquire() { ... }
    
    void release(T* obj) { ... }
    
 private:
    Pool()
    {
        _freeObjs = (T*)malloc(sizeof(T) * 100);
    }
};

class Foo
{
    int i;
public:
    void* operator new(size_t size) 
    { 
        void * p = Pool<Foo>::getInstance().acquire();
        return p; 
    } 
  
    void operator delete(void * p) 
    {  
        Pool<Foo>::getInstance().release(p);
    } 
};

int main()
{
    {
        Foo* f = new Foo();
        delete f;
    }
    
    return 0;
}

but the compiler show the following error message,

error: cannot call member function ‘Pool& Pool::getInstance() [with T = Foo]’ without object

void * p = Pool::getInstance().acquire();

Update: thanks, PaulMcKenzie After i add static to getInstance() function, the code is work.

Now, i move the overload operator new/delete to base class, if any wrong with my following code ?

class PooledObject
{
public:
    void* operator new(size_t size) 
    { 
        void * p = Pool<PooledObject>::getInstance().acquire();
        return p; 
    } 
  
    void operator delete(void * p) 
    { 
        Pool<PooledObject>::getInstance().release((PooledObject*)p);
    } 
};

class Foo : public PooledObject
{
    int i;
public:
};
1

There are 1 answers

0
PaulMcKenzie On BEST ANSWER

Your Pool<T>& getInstance() is not static. It needs to be a static function if you want to access getInstance without an object being created:

static Pool<T>& getInstance()
{
    static Pool<T> instance;
    return instance;
}