百度百科上说
L-value中的L指的是Location,表示可寻址。A value (computer science)that has an address.
R-value中的R指的是Read,表示可读。in computer science, a value that does not have an address in a computer language
但是我在某些地方又看到别人说L-value,R-value,
L:left R:right,当然我刚开始也以为是这个意思,毕竟翻译为左值右值,让人难免产生遐想。
那请问到底 L,R代表的是什么意思呢?
此外:在该篇博客上看到(i++)++,这是错误的,博主说i++返回一个临时变量, 临时变量具有const属性( 这个我在c++ primer上没看到, 请问这句话对吗 ,我看csdn上有人说没这概念,有人说这是对的),不可以更改,所以是错误的。 以下是我的理解,麻烦看一下对不对?
我:
const int temp1 = i + 1;//括号里面的i++
const int temp2 = i + 1;//括号外面的i++,因为i是先计算后自增,所以进行括号外面的i并不是自增运算后的i,而是自增运算之前的i?
temp1 = temp2;//出错,temp1 是const 变量,所以不允许赋值,出现错误
另我在dev C++中调试的时候说, [Error] lvalue required as increment operand,需要一个左值作为一个增量的立即数?应该是我左值概念没有理解清楚(我的理解就是左值是地址,右值是具体数值),所以这个我也不太理解。
2.C++primer(第五版)中说“当我们使用术语‘引用’时,其实指的是‘左值引用”
这里的 左值引用到底怎么理解呢 ?
int i = 0;
int &a = i;
int b = i;
(2)看了百度百科的“左值与右值”,根据上面说的,b = i,是将i的右值赋给了b的左值,那么 int &a = i ; 该怎么说呢?能说将i的右值赋给了a的左值吗?
(3)对于int i = 1;我们说的变量类型是指i的左值类型是int,还是右值类型是int,还是就是我说错了?因为看到书上说“引用的类型就是左值的类型”, 左值不是就是一个变量的地址吗?也能有类型? (page64(中文版) exercise2.37 题目)
以上如有说错,恳请友情指出,不胜感激!另外有时候大神看到了另外一个大神已经解答这个题目,就不想在重复回答了,我希望大神们看到之后,如果有什么补充的,额外的也可以说一下,先行谢过!
29 个回答
左值右值是非常非常久远的概念,一开始l和r就是代表left和right。但是随着语言的发展单纯左右已经无法区分lvalue和rvalue的区别了。C++11中已经不是这么笼统的概念了。一般而言,可以取地址、有名字的就是左值,反之就是右值。更为细致而言,根据C++11标准,每个表达式可分为lvalue、xvalue(expiring value)或prvalue(pure rvalue)。
有两个概念:变量表达式都是左值。左值可以当右值使用,并且在这种情况下用的是其内容。
所以对于“b = i”而言,是将i的左值作为右值使用,取i的变量的值,赋值给b的左值。
此外,临时对象不是const。++/--,前缀版本返回左值,后缀版本返回右值。
左值引用(&)这个概念和右值引用(&&)是对应的。左值引用就是常规引用,右值引用是C++11的新概念。右值引用只能绑定到一个右值。
2.37翻译错了。原文为:“Assignment is an example of an expression that yields a reference type. The type is a reference to the type of the left-hand operand.” 因为赋值操作符也是一个函数,因此也会有返回值,返回值的类型,是其左侧运算对象的引用类型。比如‘i = 3’,返回值类型就是‘int&’。
最后,给你个官方定义:
—An lvalue (so called, historically, because lvalues could appear on the left-hand side of an assignment expression) designates a function or an object.
[Example: If E is an expression of pointer type, then *E is an lvalue expression referring to the object or function to which E points. As another example, the result of calling a function whose return type is an lvalue reference is an lvalue. — end example ]
— An xvalue (an “eXpiring” value) also refers to an object, usually near the end of its lifetime (so that its resources may be moved, for example). An xvalue is the result of certain kinds of expressions involving rvalue references (8.3.2).
[Example: The result of calling a function whose return type is an rvalue reference is an xvalue. — end example ]