lvalue and rvalue for pre/postfix increment

徘徊边缘 提交于 2019-12-01 15:28:07

问题


Learning the lvalue and rvalue. The definition is whatever that can be "address of" is the left value and otherwise, it is rvalue.

I checked the operator precedence, both prefix and postfix increment has higher priority than the "address of" operator.

For the following two examples, can anyone explain a bit why the first one "&++value1" is a lvalue while the second one "&value1++" is a rvalue.

My wrong understanding for both case is: pValue1 is pointing to the value1 variable. No matter value1 is changed to 8 before or after the address correlation is built, the value1 variable always occupies one memory location and we can derive its address, right?

int value1=7;

int *pValue1=&++value1;

int *pValue1 = &value1++;

回答1:


Based on my comment you can see why the compiler is against this kind of operation. The problem lies in general implementation of postfix operator ++, which copies the object (int in this case), increments the original one and returns that preincremented copy. You can think of it like of a function that is defined in following way:

int foo_operator(int& a)
{
    int copy = a;
    a += 1;
    return copy;
}

If you try to use that function in your example, your compiler will also protest against it. The return value of that function is an rvalue.

You might now ask - what's up with the prefix operator ++? Isn't that also a function that returns a value? And the answer would be - no. Prefix operator ++ returns a reference, not a copied value, thus the 'outcome' of it can be used with operand &.



来源:https://stackoverflow.com/questions/46105726/lvalue-and-rvalue-for-pre-postfix-increment

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!