class T{ /**/ };
T fun(){ return T(); }
int main()
{
fun() = T();
return 0;
}
当我看到上面这样的代码时,我便认为这个代码无法编译通过的,因为按我所知道的,函数fun所返回的是一个临时对象,而临时对象是不能被修改的,然而fun()=T()语句便恰恰是在对临时对象进行修改。但是当我编译之后却傻眼了,居然通过了,我很纳闷。
后来在网友的帮助下,在标准中找到了答案:
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. ]
也就是说,在对内置类型进行赋值操作时,将调用内置的赋值操作符,而这种内置的要求左操作数必须是左值;而当对类类型对象进行赋值时,所调用的是重载的赋值操作符,但重载的操作符并没有要求必须使用左值,也就是说,赋值操作符的左操作数可以是右值。
后来得知,在C++中右值可以是一个对象,而“对象”就指的是“一段内存存贮区域”,但C中的右值则不是一个对象,他只是一个值。
以上内容如有不对之处,还望不惜指正。
对lvalue和rvalue的较详细介绍请看文章<Lvalues and Rvalues>:http://www.cppblog.com/zhaoyg/archive/2010/02/06/107405.html
posted on 2010-02-10 21:35
zhaoyg 阅读(433)
评论(0) 编辑 收藏 引用 所属分类:
C/C++学习笔记