user4130969
user4130969

Reputation: 31

Why implement postincrement in terms of preincrement?

Herb Sutter suggests implementing post-increment like this:

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 the guideline:

Guideline: For consistency, always implement postincrement in terms of preincrement, otherwise your users will get surprising (and often unpleasant) results.

What are these surprising (and often unpleasant) results?

Upvotes: 3

Views: 132

Answers (3)

Brian Bi
Brian Bi

Reputation: 119457

I'm pretty sure he's just saying that implementing postincrement in terms of preincrement eliminates the possibility that you accidentally implement the two operators with different logic, which would be highly confusing for users. Assuming you don't make such an error, nothing surprising or unpleasant will occur (although it might still be suboptimal because of code duplication)

Upvotes: 2

Barmar
Barmar

Reputation: 782099

This ensures that the two operators will behave equivalently in terms of how they modify the object, and only differ in their return values. If you implement the two operators separately, and you decide to modify one of them, you might forget to make the equivalent change to the other. If you implement one in terms of the other, you only have to make the change in one place. And it makes sense for preincrement to be the more fundamental one, because the only difference in postincrement is saving the old value in a temporary first.

He was probably overstating things when he said your users will get surprising results. He probably should have said might get surprising results, since it will only happen if you mess up.

Upvotes: 3

Codor
Codor

Reputation: 17605

The question is a bit philosophical. There is no "absolutely definitive" definition of the semantics of the operators, but users might expect that they have the same effect on the argument, but one returns the argument before the effect and the other after the effect. However, this can be achieved easily with the proposed implementation. No "bad effects" are guaranteed by deviation from the approach, however.

Upvotes: 1

Related Questions