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


基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09