[讨论]反思大家之前讨论过的一个问题
之前的一个帖子中提到关于自增前缀和后缀的问题,帖子在这里:http://bbs.bc-cn.net/dispbbs.asp?boardid=56&replyid=58792&id=124908&page=20&skin=0&star=1int main()
{
int x=5;
int *p=&++x;
int *q=&x++; //error C2102: '&' requires l-value
return 0;
}
Cpp1.cpp
C:\Documents and Settings\Administrator\桌面\daima\Cpp1.cpp(6) : error C2102: '&' requires l-value
最后大家争论的焦点就在为什么&++x合法,而&x++会出错,有人提到我们在c++中重载前缀自增时直接将原始对象加一,最后返回原始对象的引用,所以&++x取的是原始对象的地址,是合法的。而在后缀的实现中是通过将原始对象的值赋给一个临时对象,再将原始对象加一,最后返回临时对象的值,&x++就是取一个临时对象的地址,所以是错误的操作。我看后觉得这是有道理的,但是这只是推测,不敢确定c/c++中内置类型也是这样实现的,近来翻看Bjarne Stroustrup 的 <<The C++ Programming Language>>,发现有一段话如下:
6.2.5 Increment and Decrement
The ++ operator is used to express incrementing directly,rather than expressing it indirectly using a combination of an addition and an assignment. By definition, ++lvaue means lvalue+=1, which again means lvalue=lvalue+1 provided lvalue has no side effects. The expression denoting the object to be incremented is evalued once(ovly). Decrementint is similarly expressed by the -- operator. The operators ++ and -- can be used as both prefix and postfix operators.The value of ++x is the new(that is, incremented)value of x. For example, y=++x is equivalent to y=(x+=1). The value of x++, however, is the old value of x. For example, y=x++ is equivalent to y=(t=x,x+=1,t), where t is a variable of the same type as x.
最后两句话就是我关心的:x++的值是x自增之前的旧值。例如y=x++相当于y=(t=x,x+=1,t),其中t是和x相同类型的变量
对比y=++x is equivalent to y=(x+=1) 和 y=x++ is equivalent to y=(t=x,x+=1,t),可以看出前缀和后缀的本质差别,&++x等价于&(x+=1)即(x+=1,&x); &x++等价于&(t=x,x+=1,t)即&t.
有了Bjarne Stroustrup他老人家的话自己终于放心了。