class T{ /*
*/ };
T fun(){ return T(); }
int main()
{
fun() = T();
return 0;
}
當我看到上面這樣的代碼時,我便認為這個代碼無法編譯通過的,因為按我所知道的,函數(shù)fun所返回的是一個臨時對象,而臨時對象是不能被修改的,然而fun()=T()語句便恰恰是在對臨時對象進行修改。但是當我編譯之后卻傻眼了,居然通過了,我很納悶。
后來在網(wǎng)友的幫助下,在標準中找到了答案:
3.10.5
The result of calling a function that does not return a reference is an rvalue. User defined operators are functions, and whether such operators expect or yield lvalues is determined by their parameter and return types.
13.5.7
The identities among certain predefined operators applied to basic types (for example, ++a ≡ a+=1) need not hold for operator functions. Some predefined operators, such as +=, require an operand to be an lvalue when applied to basic types; this is not required by operator functions.
3.10
An lvalue for an object is necessary in order to modify the object except that an rvalue of class type can also be used to modify its referent under certain circumstances. [Example: a member function called for an object (9.3) can modify the object. ]
也就是說,在對內(nèi)置類型進行賦值操作時,將調(diào)用內(nèi)置的賦值操作符,而這種內(nèi)置的要求左操作數(shù)必須是左值;而當對類類型對象進行賦值時,所調(diào)用的是重載的賦值操作符,但重載的操作符并沒有要求必須使用左值,也就是說,賦值操作符的左操作數(shù)可以是右值。
后來得知,在C++中右值可以是一個對象,而“對象”就指的是“一段內(nèi)存存貯區(qū)域”,但C中的右值則不是一個對象,他只是一個值。
以上內(nèi)容如有不對之處,還望不惜指正。
對lvalue和rvalue的較詳細介紹請看文章<Lvalues and Rvalues>:http://www.shnenglu.com/zhaoyg/archive/2010/02/06/107405.html
posted on 2010-02-10 21:35
zhaoyg 閱讀(450)
評論(0) 編輯 收藏 引用 所屬分類:
C/C++學習筆記