实现无开销push_back的最佳方法是什么

what's the optimum way to implement push_back without overhead

本文关键字:最佳 方法 是什么 back 开销 push 实现      更新时间:2023-10-16

我正在尝试实现一个Queue,您可以将要添加到Queue的Object传递给它。

struct Node {
T data;
Node *next, *prev;
};    
// Push data to the back of the list.
template <class T> T& CircularQueue<T>::push_back(const T&& new_data)
{
Node* new_node = new Node();
new_node->data = std::move(new_data);
link_node(new_node, m_head);
return new_node->data;
}

我目前的方法的问题是开销太大(因为我来自C,这些事情困扰着我(。例如,图像i将添加一个来自MyClass:的对象

CircularQueue<MyClass> list;
list.push_back(MyClass(arg1, arg2));

第一个问题是,MyClass需要有一个没有参数的构造函数才能在Node* new_node = new Node();中使用,因为创建Node结构将调用其内部对象的构造函数,即MyClass。我尝试了std::vector,但它不需要这个。

第二个问题是开销太大,list.push_back(MyClass(arg1, arg2));将在堆栈中创建一个右值对象,然后发送到push_back,然后在堆中创建一一个新对象(没有参数列表(,然后使用移动分配将其所有成员移动到新对象,有没有更快的解决方案?

您可以对Node 进行template_back

template <class T> 
class CircularQueue {
template<typename... U>
T &emplace_back(U&&... u)
{
Node *new_node = new Node{{std::forward<U>(u)...}}; // <data is created here
// link_node(new_node, m_head);
return new_node->data;
}
};
void foo() {
CircularQueue<Data> x;
// Do not create a Data, pass the parameters you need to create
x.emplace_back(10, 20);
// If you actually need to, you can of course copy or move an existing Data
Data y(20, 30);
x.emplace_back(y); // copies y
x.emplace_back(std::move(y)); // moves y
}

https://godbolt.org/z/z68q77