我正在实现一个容器类(ObjectPool)。它在连续内存中维护一组模板对象。在构造时,它分配一 block 内存(相当于(模板对象的大小)*(池大小))。当向池中添加新对象时,它使用“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));
}
最佳答案
如果你使用一个T_Object&&
,它必须引用一个已经构造的T_Object
,然后你需要在你的存储中创建一个新的对象,所以这是另一个构造函数调用。
您需要类似于 emplace_back
的内容:
template<class... Args>
void emplace(Args&&... args)
{
// Allocate the template object
::new (static_cast<void*>(m_singleObject)) T_Object(std::forward<Args>(args)...);
}
将其命名为 objPool.emplace(1)
。
顺便说一句,采用 T_Object&& p_object
的 add
版本应该从 std::move(p_object)
构造包含的对象。
关于c++ - 具有新放置的右值引用(与 std::vector.push_back 类似的功能),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32388684/