lvalue and rvalue for pre/postfix increment

故事扮演 提交于 2019-12-01 16:45:36

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 &.

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