Arv*_* kr 0 c++ reference rvalue lvalue
我正在研究引用,我正在尝试一个程序将rvalue传递给函数作为引用参数,就像这样.
#include<iostream>
using namespace std;
int fun(int &x)
{
return x;
}
int main()
{
cout << fun(10);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用,当我试图通过左值时,它起作用了.
#include<iostream>
using namespace std;
int fun(int &x)
{
return x;
}
int main()
{
int x=10;
cout << fun(x);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
谁能解释我为什么会这样?
一个右值可以仅结合一个右值参考或const 左值参考; 不是非const 左值参考.所以这些都可以工作:
int fun(int const & x);
int fun(int && x);
Run Code Online (Sandbox Code Playgroud)
这是为了防止令人惊讶的行为,其中函数可能会修改临时值而不是您认为可能的变量; 例如:
void change(int & x) {++x;}
long x = 42;
change(x);
cout << x; // would print 42: would have changed a temporary 'int', not 'x'
Run Code Online (Sandbox Code Playgroud)