c++ - 非常量引用只能绑定(bind)到左值

标签 c++

谁能解释一下如何模拟这个错误?还有这提示什么。

"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

鉴于上述定义,引用 rscrs 与引用 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/

相关文章:

c++ - 为什么不允许 `std::uniform_int_distribution<uint8_t>` 和 `std::uniform_int_distribution<int8_t>`?

c++ - 将以毫秒为单位的时间戳转换为boost中的时区

c++ - super 对撞机二维阵列 : generative nesting : wrap/size issues

c++ - 如何从 QStringList 中删除空字符串和空字符串?

c++ - 从数组列表中用户搜索一个数字,如果没有找到,则只显示一个未找到的消息,而不是多次

c++ - 如何继承boost.process中的某些fd,同时关闭所有其他fd

c++使用for循环的最佳方法

c++ - 引用 "auto"函数作为模板参数

c++ - 带有 Aero 主题(阴影)的窗口定位 - 0,0 处的窗口隐藏了一些边框

c++ - ldd 显示重复的共享库