如果我将现有对象推入队列:
struct Node {int x; int y;};
std::vector<Node> vec;
vec.push_back(Node(1, 3));
std::queue<Node> q;
q.push(vec[0]);
Run Code Online (Sandbox Code Playgroud)
在最后一行,不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;
};
Run Code Online (Sandbox Code Playgroud)
对于您的程序,这会打印
创建节点 移动节点 复制节点
自从
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.
Run Code Online (Sandbox Code Playgroud)
小智 5
当您分配右值引用时,它将被复制。如果您分配左值引用,它将被移动。(临时对象)。
要检查,请使用复制构造函数/运算符并移动构造函数/运算符重载:
#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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
535 次 |
| 最近记录: |