インスタンス クリエータ クラスを引数としてオブジェクト プールに渡すことができるように、既存のオブジェクト プール クラスを変更しようとしています。基本的に、実際のオブジェクトの構築をメモリプールから除外できるようにしたいので、プールするインスタンスを作成する方法の自由度が高まります。
オブジェクト プールの定義は次のとおりです。
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メソッドで何かを変更する必要があるかどうかは、今のところわかりませんが、今のところそうではないと思います。
あなたの助けに感謝!