为什么允许通过常量引用而不是通过普通引用传递 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).

相关文章