[英]passing Rvalues into a copy constructor and assignment operator
Passing an Rvalue into a copy constructor or assignment operator seems to me to be a very important thing to be able to do. 在我看来,将Rvalue传递给复制构造函数或赋值运算符似乎是一件非常重要的事情。 For example:
例如:
int a = b+c;
or 要么
int a;
a = b+c;
Without this it would be hard to do math calculations. 没有这个,将很难进行数学计算。
Yet I am unable to do this with a class. 但是我无法在全班学习。 Here's my code
这是我的代码
#include <iostream>
using namespace std;
struct node{
public:
node(int n){
node* ptr = this;
data = 0;
for (int t=0; t<n-1; t++){
ptr -> next = new node(1);
ptr = ptr -> next;
ptr -> data = 0;
}
ptr -> next = NULL;
}
node(node &obj){
node* ptr = this;
node* optr = &obj;
while (true){
ptr -> data = optr -> data;
optr = optr -> next;
if (optr == NULL) break;
ptr -> next = new node(1);
ptr = ptr -> next;
}
}
void operator=(node &obj){
delete next;
node* ptr = this;
node* optr = &obj;
while (true){
ptr -> data = optr -> data;
optr = optr -> next;
if (optr == NULL) break;
ptr -> next = new node(1);
ptr = ptr -> next;
}
}
~node(){
if (next != NULL) delete next;
}
private:
double data;
node* next;
};
node func1(){
node a(1);
return a;
}
void func2(node a){
node b(1);
b = func1();
}
int main(){
node v(3);
func1();
func2(v);
}
I am given this compiling error: 我收到此编译错误:
expects an l-value for 1st argument
how can I write a copy constructor and assignment operator that take r-values as well as l-values? 我该如何编写一个既带有r值又带有l值的复制构造函数和赋值运算符?
Thanks for the help 谢谢您的帮助
You are misusing the copy c'tor and assignment operator to achieve a move. 您正在滥用复制控制器和赋值运算符来实现移动。 Conventionally, copy c'tors and assignment operators receive
const
references, which can bind to both r-values and l-values. 按照惯例,复制c'tors和赋值运算符会接收
const
引用,该引用可以绑定到r值和l值。 However, if you'd like to achieve a move, then use the move c'tor and assignment operator: 但是,如果您想实现移动,请使用移动控制器和赋值运算符:
node(node&& n){ /* pilfer 'n' all you want */ }
node& operator=(node&& n) { /* ditto */ }
Conflating move semantics with copying only causes woe later on. 将移动语义与复制混淆在一起只会在以后造成麻烦。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.