Why implement post-increment in terms of pre-increment?

Herb Sutter suggests implementing the subsequent increment as follows:

T T::operator++(int)() {
    auto old = *this; // remember our original value
    ++*this;          // always implement postincr in terms of preincr
    return old;       // return our original value
}

      

With directive:

Guiding principle . For consistency, always do post-increment in terms of pre-increment, otherwise your users will be surprised (and often frustrating).

What are these unexpected (and often unpleasant) results?

+3


source to share


3 answers


This ensures that the two operators behave the same in terms of how they modify the object, and differ only in their return values. If you are executing two statements separately and you decide to change one of them, you may forget to make an equivalent change to the other. If you are implementing one from the perspective of the other, you only need to make changes in one place. And it makes sense for preincrement to be more fundamental, because the only difference in postincrement is to keep the old value over time.



He was probably exaggerating when he said your users would get unexpected results. He probably should have said that this can lead to unexpected results, as it will only happen if you screw up.

+3


source


I'm sure he just said that implementing postincrement in terms of pre-increment eliminates the possibility that you accidentally implement two operators with different logic, which will be very confusing for users. Assuming you don't make such a mistake, nothing unexpected or unpleasant will happen (although it may be suboptimal due to code duplication)



+2


source


The question is a bit philosophical. There is no absolutely "definitive" definition of operator semantics, but users can expect them to have the same effect on an argument, but one returns the argument before the effect and the other after the effect. However, this can easily be achieved with the proposed implementation. However, "bad consequences" are guaranteed by deviations from the approach.

+1


source







All Articles