队列创建副本吗? [英] does queue create a copy?
本文介绍了队列创建副本吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我将现有对象推入队列:
If I push an existing object into a queue:
struct Node {int x; int y;};
std::vector<Node> vec;
vec.push_back(Node(1, 3));
std::queue<Node> q;
q.push(vec[0]);
在最后一行,q
是否存储 地址(指针或引用,除了对象本身)vec[0]
,还是将整个Node
对象复制到q
中?
At the last line, does q
store the address (pointer or reference, whatever except the object itself) of vec[0]
, or does it copy the whole Node
object into q
?
推荐答案
它会在您分配右值引用时被复制.如果您分配左值引用,它将被移动.(临时对象).
It will get copied as you assign an rvalue reference. It will get moved if you assign an lvalue reference. (temporary object).
要检查,使用复制构造函数/运算符和移动构造函数/运算符重载:
To check, use copy constructor / operator and move constructor / operator overloading:
#include <iostream>
#include <vector>
#include <queue>
struct Node {
int x;
int y;
Node(int x, int y) : x(x), y(y)
{
std::cout << "constructor" << std::endl;
}
Node(Node const & original) : x(original.x), y(original.y)
{
std::cout << "copy constructor" << std::endl;
}
Node(Node const && original) : x(original.x), y(original.y)
{
std::cout << "move constructor" << std::endl;
}
Node & operator=(Node const & original) {
std::cout << "assignment operator" << std::endl;
if(this != &original) {
x = original.x;
y = original.y;
}
return *this;
}
Node & operator=(Node const && original) {
std::cout << "move operator" << std::endl;
if(this != &original) {
x = original.x;
y = original.y;
}
return *this;
}
};
int main() {
std::vector<Node> v;
Node n(1,3); // constructor
Node m(3, 4); // constructor
m = n; // assignment operator
n = Node(2, 3); // constructor + move operator
v.push_back({1,2}); // constructor + move constructor
v.push_back(n); // copy constructor
std::queue<Node> q;
q.push(v[0]); // copy constructor
return 0;
}
这篇关于队列创建副本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文