2012年12月25日 星期二

[C++] Lvalues and Rvalues

Lvalue and Rvalue在C++裡面算是一個很重要的觀念
但是一直都沒搞得很懂, 所以常常看一些技術文件時都還是霧煞煞
這邊就暫時間做點筆記吧

Lvalue: 就是一個運算式後還保留其狀態的一個物件 就是Lvalue; 也就是說 所有的變數(variables)包含nonmodifiable, const 的變數都是Lvalue.  這邊一個重點是 const的變數也是Lvalue
Lvalue is a 1. named object. 2. lvalue reference.

Rvalue: 就是一個運算式過後其狀態就不會被保留了, 也就是一個暫存的數值
Rvalue is an unnamed temporary object

另一種說法(非完全正確,  但是可以依此來稍做判斷)
能出現在assignment 運算子(=)的左邊的稱為Lvalue, 而只能出現在右邊的稱為Rvalue

這邊只有說出現在左邊的是Lvalue, 但沒說Lvalue不能出現在右邊, 因此Lvalue在=運算子的左右兩邊都是被允許的, 而Rvalue是不能出現在左邊的; 這邊有沒有注意到, Lvalue是可以被放到右邊的, 也就是說Lvalue也可以被當作Rvalue, 但是Rvalue就不能被當作是Lvalue

但是Lvalue有個例外就是了, 屬於non-modifiable的Lvalue也是不允許出現在= 運算子的左邊的, 因為它(non-modifiable)是沒辦法被修改的, 出現在左邊就違反了non-modifiable的特性.
而non-modifiable Lvalues有哪些呢? 包含了有
1. An array type
2. An const-qualified type
3. An incomplete type
4. A structure or union type with one of its members qualified as a const type

以下是一些運算子的要求

Operator
Requirement
& (unary) Operand must be an lvalue.
++ -- Operand must be an lvalue. This applies to both prefix and postfix forms.
= += -= *= %= <<= >>= &= ^= |= Left operand must be an lvalue.


另外 in C++, a function call that returns a reference is a Lvalue. Otherwise, a function call is a Rvalue expression.
例子:


Expression
Lvalue
x = 42 x
*ptr = newvalue *ptr
a++ a
 int& f() The function call to f()



接下來就是更加複雜抽象的Lvalue Reference and Rvalue Reference了
這在就在下一篇文章在紀錄

reference:
1. http://msdn.microsoft.com/en-us/library/f90831hc.aspx
2. http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Flvalue.htm




1 則留言: