右值不起参考作用
rvalue not working for reference
我在研究引用,我正在尝试一个程序将右值作为引用参数传递给函数,就像这样。
#include<iostream>
using namespace std;
int fun(int &x)
{
return x;
}
int main()
{
cout << fun(10);
return 0;
}
但这不起作用,当我试图传递一个左值时,它起作用了。
#include<iostream>
using namespace std;
int fun(int &x)
{
return x;
}
int main()
{
int x=10;
cout << fun(x);
return 0;
}
有人能解释一下为什么会发生这种事吗?
右值只能绑定到右值reference或const
左值值引用。所以这两种方法都可以:
int fun(int const & x);
int fun(int && x);
这是为了防止函数可能修改临时值而不是您认为可能修改的变量的意外行为;例如:
void change(int & x) {++x;}
long x = 42;
change(x);
cout << x; // would print 42: would have changed a temporary 'int', not 'x'
您正试图在fun(int &x)
中传递引用。&
符号表示"传递参数地址/引用"。目前,您正在尝试混合可修改的左值和常量右值,这是错误的fun(const int &x)
会很好地工作,这可能是你想要做的
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 未在作用域中声明unordered_map
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++为什么尽管我调用了void函数,它却不起作用
- C++错误消息*成员参考.**初学者*
- 为什么在保护模式下继承升级不起作用
- 循环在计数器中不起作用
- 有没有一种方法可以在编译时获得作用域类名
- 在其他文件中创建类时在 c++ 项目中不起作用
- 在决定是通过参考还是通过价值时,尺寸真的是一个问题吗
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 为什么二进制搜索在我的测试中不起作用
- C++quit()函数中可能存在作用域问题
- 恒定参考如何起作用
- 将参考类型作为嵌套模板结构中的模板参数作为模板参数不起作用
- 基于范围的循环中的const参考不起作用
- 为什么此C 代码不起作用 - 试图删除集合中的元素时,请参考错误
- 右值不起参考作用
- 为什么具有通用参考的重载(使用 enable_if)不起作用?