[英]About assigning values to functions
I have the following code snippet:我有以下代码片段:
#include <iostream>
using namespace std;
class X {
int i;
public:
X(int ii = 0);
void modify();
};
X::X(int ii) { i = ii; }
void X::modify() { i++; }
X f5() { return X(); }
const X f6() { return X(); }
void f7(X& x) {
x.modify();
}
int f()
{
return 18;
}
int main() {
f5() = X(1); /// Why does this work??? Isn't f5() an rvalue ??? (*)
f5().modify();
/// f7(f5()); /// cannot bind non-const lvalue reference of type 'X&' to an rvalue of type X; not contradictory with (*)?
//! f6() = X(1);
//! f6().modify();
//! f7(f6());
//! f() = 12; this also doesn't work
return 0;
}
How can f5() = X()
work? f5() = X()
如何工作? Isn't f5() a rvalue? f5() 不是右值吗? Then why doesn't
f() = 12
work?那么为什么
f() = 12
不起作用呢? What is the difference?有什么区别? Also, the error that
f7(f5())
generates doesn't say that f5()
is a rvalue?另外,
f7(f5())
生成的错误并不是说f5()
是右值吗? What am I missing?我错过了什么?
f5()
indeed yields an rvalue and f5() = X(1);
f5()
确实产生了一个右值,并且f5() = X(1);
invokes implicitly generated move operator =
.调用隐式生成的移动
operator =
。 It will stop working if this operator is deleted: void operator =(X &&) = delete;
如果删除此运算符,它将停止工作:
void operator =(X &&) = delete;
. .
Also the error that f7(f5()) generates does say that f5()
is an rvalue: f7(f5()) 生成的错误也确实表明
f5()
是一个右值:
to an rvalue of type X
到类型 X 的右值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.