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 值?
基础教程推荐
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- c++ STL设置差异 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
