Original Post
Hello, I have read that stl is really slow and that object pools are the way to store particles and similar. here is the class I have written
Is this good to go, or are there likely to be problems?
template <typename Type>
class ObjectPool
{
// number of elements added to the pool
unsigned int numElements;
// pointer to the memory pool
Type* Pool;
// number of elements the pool has space for without reallocating
// should always be modified alongside Pool
unsigned int poolSize;
// Both <Pool> and <poolSize> are ONLY MODIFIED by the _Realloc function (and ctor)
public:
// reserves space for <count> elements
ObjectPool(unsigned int count = 1024)
{
numElements = 0;
poolSize = 0;
Pool = NULL;
_Realloc(count);
}
~ObjectPool()
{
Clear();
}
// beware; pointers to old elements may still be valid after this!
void Clear()
{
numElements = 0;
}
void Add(Type* elem)
{
if (NULL == elem)
return;
if (numElements+1 == poolSize)
_Realloc(numElements * 2);
memcpy(&Pool[numElements], elem, sizeof(Type));
numElements ++;
}
// WARNING: Invalidates all pointers to elements in the pool
void Remove(unsigned int index)
{
if (index < 0 || index >= numElements)
return;
Type* newPool = new Type[poolSize];
// for copying
int elemsBefore = index;
int elemsAfter = (numElements - index) - 1;
memcpy(newPool, Pool, elemsBefore * sizeof(Type));
memcpy(&newPool[index], &Pool[index+1], elemsAfter * sizeof(Type));
numElements--;
}
// get the number of elements added to the pool
unsigned int Size()
{
return numElements;
}
// get the space reserved for pool elements
unsigned int Space()
{
return poolSize;
}
// get the memory footprint of the pool
unsigned int MemorySize()
{
return poolSize * sizeof(Type);
}
// returns true if succeeded.
// if success, (*out) points to the <index>th element
// if failed, (*out) should not be trusted
bool Get(unsigned int index, Type** out)
{
if (index < 0 || index >= numElements || NULL == out)
{
return false;
}
// TODO: safety first
*out = &Pool[index];
return true;
}
private:
void _Realloc(unsigned int newSize, bool copy = true)
{
Type* oldPool = Pool;
if (newSize > 0)
{
Pool = new Type[newSize];
}
else
{
Pool = NULL;
}
poolSize = newSize;
if (oldPool)
{
if (Pool && copy)
memcpy(Pool, oldPool, numElements * sizeof(Type));
delete[] oldPool;
}
}
};
Is this good to go, or are there likely to be problems?