非const引用只能绑定到左值

Pav*_*avi 14 c++

有人可以解释一下如何模拟这个错误吗?以及这个抱怨的内容.

"在C++中,非const引用只能绑定到左值"

Nic*_*tti 47

一个左值是大致!不论在赋值语句的左侧.引用为其他对象提供别名:

std::string s;
std::string & rs = s;  // a non-const reference to s
std::string const & crs = s; // a const reference to s
Run Code Online (Sandbox Code Playgroud)

鉴于上述定义,引用rscrs与引用相同s,除了您不能修改引用的字符串crs,因为它是const.变量是左值,因此您可以将非const引用绑定到它.相反,您可以将const引用绑定到临时值,如下所示:

std::string const & crs1 = std::string();
Run Code Online (Sandbox Code Playgroud)

但是以下是非法的:

std::string & rs1 = std::string();
Run Code Online (Sandbox Code Playgroud)

这是因为使用非const引用意味着您要修改引用的对象.但是,当引用超出范围时,绑定到引用的临时值将被销毁.由于C++创建临时对象时并不总是直观,因此不允许将它们绑定到非const引用,以避免因为您喜欢更改对象而感到不愉快,只是为了看到它稍后会破坏一些语句.


Oli*_*rth 6

这意味着你不能做这样的事情:

void foo(int &x) { ... }
int bar()        { ... }

foo(bar());
Run Code Online (Sandbox Code Playgroud)

您将需要做出foo采取const参考,或分配的结果bar()给一个变量,然后传递到成foo.