Post-increment in assignment to reference c++

核能气质少年 提交于 2020-01-17 05:41:40

问题


Assume I have this code:

int i = 2;
int &ref = i++;

Now, I understand that reference can not be initiaizied with rvalue, but I can not understand why ref isn't initialized with lvalue, meaning here, i, and after that i incremented.

Moreover, in the following case:

   int i = 2;
   const int &ref = i++;
   cout << ref << endl;

2 will be printed, and it means that ref initialized with i before increment, i.e. initialized with lval. After that ref is incremented, but ref is const.

Can someone explain me what I am missing here?


回答1:


Post-incrementing an int does not result in an lvalue. A hypothetical implementation might look like this:

int operator++(int& i) {
    int temp = i;
    ++i;
    return temp;
}

As you can see, a copy needs to be made and that is returned by value.

Pre-increment does result in an lvalue because no copy is required, so the result is a reference to the original.

Your second example works because rvalues can bind to references-to-const.




回答2:


i++ doesn't return i, but a temporary copy, that was taken before i got incremented. That's why it is called POST increment, because it increments thew variable AFTER it retained a copy of the current state.




回答3:


Post incrementing an int does not return in lvalue. i++ returns a temporary copy before incrementing itself.



来源:https://stackoverflow.com/questions/32560823/post-increment-in-assignment-to-reference-c

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