【发布时间】:2015-11-30 01:24:56
【问题描述】:
我正在实现一个容器类 (ObjectPool)。它在连续内存中维护一个模板对象数组。在构造时,它分配一块内存(相当于(模板对象的大小)*(池大小))。向池中添加新对象时,它使用“placement new”运算符在特定内存地址创建对象(并自动调用模板对象的构造函数)。
如何实现 ObjectPool.add() 方法,以接受模板对象并将其添加到对象池,而不调用它的构造函数两次(例如在 std::vector.push_back() 中实现的功能)?
为简单起见,在这种情况下,ObjectPool 类只包含一个模板对象,而不是一个数组。
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));
}
【问题讨论】:
标签: c++ templates c++11 rvalue placement-new