我尝试修改现有的对象池类,以便能够将实例创建者类作为参数传递给对象池。基本上,我希望能够将实际的对象构造排除在内存池之外,这样我就可以更自由地创建要池化的实例。
这是对象池定义:
template <
typename T,
typename InstanceCreator = DefaultInstanceFactory<T>
>
class ObjectPool : private noncopyable {
...
}
所以我会像这样创建一个 ObjectPool
ObjectPool<int> intPool((DefaultInstanceFactory<int>()));
或者
ObjectPool<IntClass, IntClass::InstanceFactory> intPool (IntClass::InstanceFactory (1));
默认实例创建者如下所示
template <typename T>
class DefaultInstanceFactory {
public:
T * operator ()() const {
return new T;
}
};
在该 ObjectPool 类内部是一个嵌套类,用于存储项目
class PooledItem {
public:
char data[OBJECT_SIZE];
PooledItem * next;
bool initialized;
PooledItem()
: initialized(false) {}
~PooledItem() {
// --- call T destructor
if (initialized)
cast()->~T();
}
T * cast() {
return reinterpret_cast<T *>(data);
};
};
有一个获取对象的 borrowObject 方法,这是我的实际问题:
T * borrowObject() {
PooledItem * item = getItem();
T * obj = item->cast();
if (! item->initialized) {
// old original line, call the defaut constructor of T
new (obj) T();
// how to integrate the external Instance Creator at this point?
//new (instCreator_ ()) T(1);
//instCreator_ ();
item->initialized = true;
}
if (obj == NULL) {
throw ObjectPoolException(
"Object is NULL!", __FILE__, __LINE__, __FUNCTION__);
}
return obj;
}
在上述方法中,我标记了实际的问题行。我不知道如何new (obj) T()
用外部实例创建者替换放置新行,以重用该内存。
为了完整起见,将对象返回到池中的方法如下所示
void returnObject(T * obj) {
// --- Get containing PooledItem pointer
PooledItem * item = reinterpret_cast<PooledItem *>(obj);
// --- Make sure object came from this pool
if (item->next != reinterpret_cast<PooledItem *>(this)) {
// throw Exception
}
// --- Destroy object now if we want to reconstruct it later
if (destroyOnRelease) {
item->cast()->~T();
item->initialized = false;
}
谁能给我一些帮助如何修改方法以便正确集成外部实例创建者?到目前为止,我不知道是否需要更改 returnObject 方法中的某些内容,到目前为止我认为不需要。
感谢你的帮助!