为什么允许通过常量引用而不是通过普通引用传递 R 值? [英] Why is it allowed to pass R-Values by const reference but not by normal reference?

查看:26
本文介绍了为什么允许通过常量引用而不是通过普通引用传递 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 值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆