实现无开销push_back的最佳方法是什么
what's the optimum way to implement push_back without overhead
我正在尝试实现一个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
相关文章:
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 在C++中向零方向近似的最佳方法
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 检测win32服务创建和删除的最佳方法
- 在C++中样板"冷/never_inline"错误处理技术的最佳方法是什么?
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 将线程中的数据存储到全局容器的最佳方法?
- 将一系列整数放入类的最佳方法是什么?
- 在派生类中使用基类的私有成员变量的最佳方法
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- Qt - QVector 和模型视图 - 从列表视图获取自定义类的最佳方法是什么?
- 使用 Git 处理 C++ Visual Studio 2019 解决方案的外部依赖项源代码管理的最佳方法是什么?
- 比较两个节点坐标的最佳方法是什么?
- 在nodejs中使用本机代码的最佳方法是什么?
- 将 pybind11 绑定标记为已弃用的最佳方法
- C++:将向量传递到构造函数以创建成员变量的最佳方法?
- C++中变量混叠的最佳方法
- 读取大文件(>2GB)(文本文件包含以太网数据)并通过不同参数随机访问数据的最佳方法是什么?