gpt4 book ai didi

c++ - 具有新放置的右值引用(类似于 std::vector.push_back 的功能)

转载 作者:太空宇宙 更新时间:2023-11-04 16:07:53 24 4
gpt4 key购买 nike

我正在实现一个容器类 (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));
}

最佳答案

如果你拿一个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_objectadd 版本应该从std::move(p_object) 构造包含的对象。

关于c++ - 具有新放置的右值引用(类似于 std::vector.push_back 的功能),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32388684/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com