I am implementing a container class (ObjectPool). It maintains an array of template objects in contiguous memory. On construction, it allocates a block of memory (equivalent to (size of template object)*(pool size)). When adding new objects to the pool, it uses 'placement new' operator to create an object at a specific memory address (and automatically call template object's constructor).
How do I implement the ObjectPool.add() method, to accept a template object and add it to the object pool, without calling it's constructor twice (functionality as implemented in std::vector.push_back() for example)?
For simplicity, in this case, ObjectPool class contains only one template object instead of an array.
class FooClass
{
public:
FooClass(int p_testValue) : m_testValue(p_testValue)
{
std::cout << "Calling constructor: " << m_testValue << std::endl;
}
int m_testValue;
};
template <class T_Object>
class ObjectPool
{
public:
ObjectPool()
{
// Allocate memory without initializing (i.e. without calling constructor)
m_singleObject = (T_Object*)malloc(sizeof(T_Object));
}
// I have tried different function arguments (rvalue reference here, amongs others)
inline void add(T_Object &&p_object)
{
// Allocate the template object
new (m_singleObject) T_Object(p_object);
}
T_Object *m_singleObject;
};
int main()
{
ObjectPool<FooClass> objPool;
objPool.add(FooClass(1));
}