谁能解释一下如何模拟这个错误?还有这提示什么。
"A non-const reference may only be bound to an lvalue" in C++
最佳答案
lvalue 大致是赋值语句左侧的任何内容。引用为其他对象提供别名:
std::string s;
std::string & rs = s; // a non-const reference to s
std::string const & crs = s; // a const reference to s
鉴于上述定义,引用 rs
或 crs
与引用 s
相同,只是不能修改引用的字符串通过 crs
,因为它是 const。变量是左值,因此您可以绑定(bind)非 const 引用。相反,您可以将 const 引用绑定(bind)到临时值,如下所示:
std::string const & crs1 = std::string();
但以下内容是非法的:
std::string & rs1 = std::string();
这是因为使用非常量引用意味着您要修改被引用的对象。但是,当引用超出范围时,绑定(bind)到引用的临时对象将被销毁。由于 C++ 创建临时对象并不总是直观的,因此不允许将它们绑定(bind)到非 const 引用,以避免您随意更改对象的不愉快意外,只是稍后看到它破坏了一些语句。
关于c++ - 非常量引用只能绑定(bind)到左值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6967927/