c++ - 关于为函数赋值
问题描述
我有以下代码片段:
#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()
是一个右值?我错过了什么?
解决方案
f5()
确实会产生一个右值并f5() = X(1);
调用隐式生成的 move operator =
。如果删除此运算符,它将停止工作:void operator =(X &&) = delete;
。
f7(f5()) 生成的错误也确实说这f5()
是一个右值:
到类型 X 的右值
推荐阅读
- wordpress - 如何使用 WordPress Rest API 在 Yoast 中添加元标题和描述?
- c++ - 如何在cmake上添加C++标志-Wno-unused-function?
- react-native - `react-native-iap`:在 Android 上添加 IAP 之前,您是否必须部署到生产环境?
- terraform - terraform 控制台:表达式后的额外字符
- javascript - TypeError:无法读取未定义的属性“导入”(react-quill)
- reactjs - 在 React Native 中应用 adjustsFontSizeToFit 后获取字体大小
- html - XSLT 模板用字符串替换字符串,包括 HTML 标签
- gitlab-ci - 如果在 for 循环 gitlab-ci.yml
- reactjs - 无法水平对齐 Material-UI Autocomplete & Material-UI FormControl
- javascript - 在 jquery UI 自动完成功能中,在列表中每个项目的末尾添加一个按钮