Order of incrementing and dereferencing pointer in C++

前端 未结 3 778
既然无缘
既然无缘 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:25

    Precedence is only a rule for how the code should be parsed. ++ comes first, and * comes second. But when the code is executed, you have to consider what the operators actually do.

    In your case, the following happens:

    1. A copy of begin is made.
    2. The original is incremented.
    3. The copy is returned.
    4. The copy is dereferenced.
    5. The copy is assigned to min_value.

    That's just how the post-increment operator works, and it's also how you write the operator when you overload it for your own types:

    T operator++(int)
    {
        T copy = *this;
        ++(*this);
        return copy;
    }
    

    Actually, in the case of the built-in post-increment operator, incrementation does not necessarily have to be step 2. It could also happen at a later point, as long as the observable behaviour is the same. For example, nothing stops the compiler from incrementing the original value after it has returned the copy. You could not perform such a thing in your own, overloaded operator, of course.

提交回复
热议问题