简体   繁体   中英

How to write an generic object pool in c++

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:
};

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM