Why is it allowed to pass R-Values by const reference but not by normal reference?(为什么允许通过常量引用而不是通过普通引用传递 R 值?)
问题描述
下面的程序
void display(const int& a)
{
cout << a ;
}
如果使用这样的文字调用将起作用
will work if called with a literal like this
display(5);
但如果没有 const
它将无法工作.
but without the const
it won't work.
那么 const
引用如何一直指向 R 值(匿名变量)?
So how can a const
reference keep pointing to an R-Value (anonymous variable)?
推荐答案
最后一个问题:
const 引用如何一直指向 R 值(匿名变量)
how can a const reference keep pointing to an R-Value (anonymous variable)
这里是回答.C++ 语言说局部常量引用会延长临时值的生命周期,直到包含范围结束,但可以节省复制构造的成本(即,如果您要使用局部变量).
Here is the answer. The C++ language says that a local const reference prolongs the lifetime of temporary values until the end of the containing scope, but saving you the cost of a copy-construction (i.e. if you were to use an local variable instead).
这篇关于为什么允许通过常量引用而不是通过普通引用传递 R 值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么允许通过常量引用而不是通过普通引用传递 R 值?


基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01