如果我将现有对象插入队列:
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
?
最佳答案
它确实创建了一个拷贝。事实上,您总是可以通过覆盖复制或移动构造函数来找出复制或移动发生的位置:
class Node
{
public:
Node(int x, int y) { std::cout << "Create node" << std::endl; }
Node(const Node&) { std::cout << "Copy node" << std::endl; }
Node(Node&&) { std::cout << "Move node" << std::endl; }
virtual ~Node() = default;
};
对于您的程序,这会打印Create node Move node Copy node
Since
std::vector<Node> vec;
vec.push_back(Node(1, 3)); // Creates a temporary node and moves it into the vector.
std::queue<Node> q;
q.push(vec[0]); // Copys the node.
关于c++ - 队列创建拷贝吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62889877/