有必要有一个临时或字面值有一个右值吗? [英] Is it necessary to have a temporary or a literal to have an rvalue?
问题描述
此问题询问是否所有临时值都是有价值的。
This question asks if all temporaries are rvalue.
答案是否定的,因为如果我们考虑这个表达式:
The answer is no, because if we consider this expression:
const int &ri = 2 + 3;
那么,非常相同的临时(2 + 3)
,这里是一个右值,可以使用
作为后续表达式中的左值:
then, the very same temporary (2 + 3)
, which is an rvalue here, can be used
as an lvalue in a subsequent expression:
const int *pi = &ri;
所以这个临时值不是(只有)右值。
so this temporary is not (only) an rvalue.
逻辑语句 temporary ==>
The logic statement temporary ==> rvalue
is then false.
但是,我们无法写
const int &ri = &(2 + 3); // illegal, 2 + 3 -> temporary -> rvalue
或
int *i = &4; // illegal, 4 is an rvalue (literal)
或
int foo();
int *i = &foo(); // illegal, foo() -> temporary -> rvalue
因此我的问题是,我们可以在某个表达式中生成一个右值,而不是
临时还是文字?是 rvalue ==> (临时或字面)
true?
Thus my question is, can we generate an rvalue in a certain expression without
having a temporary or a literal? Is rvalue ==> (temporary or literal)
true?
推荐答案
强> r值。有一个特殊的规则允许const引用和r值引用绑定到r值,并且这将临时对象的生命周期延长到引用的生命周期(参见12.2(5)),但这不会使临时 - 对象表达式的任何更少的r值。
Expressions that yield temporary objects are r-values. There's a special rule which allows const-references and r-value references to bind to r-values, and this extends the lifetime of the temporary object to that of the reference (see 12.2(5)), but that does not make the temporary-object expression any less of an r-value.
但是,一旦绑定到引用,引用变量本身就有一个名称,因此引用表达式是l -l值。
However, once bound to a reference, the reference variable itself has a name, and thus the reference expression is an l-lvalue.
不要混淆表达式,变量和对象。
Don't confuse expressions, variables and objects.
这篇关于有必要有一个临时或字面值有一个右值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!