右值不起参考作用

rvalue not working for reference

本文关键字:参考 作用      更新时间:2023-10-16

我在研究引用,我正在尝试一个程序将右值作为引用参数传递给函数,就像这样。

#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)会很好地工作,这可能是你想要做的