Order of incrementing and dereferencing pointer in C++

前端 未结 3 813
既然无缘
既然无缘 2021-01-14 10:06

I tutor students in C++, and recently came across a problem involving pointer arithmetic with array names. The main thing I\'m confused about is the statement



        
3条回答
  •  天命终不由人
    2021-01-14 10:42

    You should not confuse the return value of an operator and the priority.

    The first is dealing with what the operator returns, the second deals with when something happens.

    So if you have:

    T min_value = *begin++;
    

    Here is how it works:

    1. operator++ - it increments the pointer, but returns the pointer that was there originally.
    2. operator* - dereferences the pointer returned previously, returns T that it pointed to.
    3. operator= stores left-hand side into right-hand side, returns right-hand side.

    You don't use the last return value, but you theoretically could.

    Note here, that in #2 you use the return from #1, rather than accessing the pointer again.

提交回复
热议问题