如何在 C++ 中编写通用对象池
How to write an generic object pool in c++
我想写一个通用的对象池class并且对象池应该是单例的,很容易随处访问那个对象池。
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;
}
但编译器显示以下错误消息,
错误:无法在没有对象的情况下调用成员函数‘Pool& Pool::getInstance() [with T = Foo]’
void * p = Pool::getInstance().acquire();
更新:谢谢,PaulMcKenzie
在我将静态添加到 getInstance() 函数后,代码就可以工作了。
现在,我将重载运算符 new/delete 移动到基础 class,如果我的以下代码有任何错误?
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:
};
你的 Pool<T>& getInstance()
不是 static
。如果您想在不创建对象的情况下访问 getInstance
,它需要是一个 static
函数:
static Pool<T>& getInstance()
{
static Pool<T> instance;
return instance;
}
我想写一个通用的对象池class并且对象池应该是单例的,很容易随处访问那个对象池。
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;
}
但编译器显示以下错误消息,
错误:无法在没有对象的情况下调用成员函数‘Pool& Pool::getInstance() [with T = Foo]’
void * p = Pool::getInstance().acquire();
更新:谢谢,PaulMcKenzie 在我将静态添加到 getInstance() 函数后,代码就可以工作了。
现在,我将重载运算符 new/delete 移动到基础 class,如果我的以下代码有任何错误?
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:
};
你的 Pool<T>& getInstance()
不是 static
。如果您想在不创建对象的情况下访问 getInstance
,它需要是一个 static
函数:
static Pool<T>& getInstance()
{
static Pool<T> instance;
return instance;
}