问题描述
我想编写一个通用的对象池类,并且对象池应为单例,很容易在任何地方访问该对象池。
# Use a separate file for the secret key
with open('/path/to/the/secretkey.txt') as f:
SECRET_KEY = f.read().strip()
错误:在没有对象的情况下无法调用成员函数“ Pool&Pool :: getInstance()[with T = Foo]”
void * p = Pool :: getInstance()。acquire();
更新:谢谢PaulMcKenzie 将static添加到getInstance()函数后,代码即可工作。
现在,如果我的以下代码有任何错误,我将重载运算符new / delete移至基类?
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<T>& getInstance()
不是static
。如果要在没有创建对象的情况下访问static
,则它必须是getInstance
函数:
static Pool<T>& getInstance()
{
static Pool<T> instance;
return instance;
}