首页 > 解决方案 > 关于为函数赋值

问题描述

我有以下代码片段:

#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;
}

怎么可能f5() = X()工作?f5() 不是右值吗?那为什么不行f() = 12呢?有什么区别 ?此外,f7(f5())生成的错误并没有说这f5()是一个右值?我错过了什么?

标签: c++assignrvalue

解决方案


f5()确实会产生一个右值并f5() = X(1);调用隐式生成的 move operator =。如果删除此运算符,它将停止工作:void operator =(X &&) = delete;

f7(f5()) 生成的错误也确实说这f5()是一个右值:

到类型 X 的右值


推荐阅读