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 值?


基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09