Post increment and decrement

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Sun Mar 15 01:45:51 PDT 2015


On Saturday, March 14, 2015 15:35:24 Ali Çehreli via Digitalmars-d wrote:
> On 03/14/2015 03:23 PM, deadalnix wrote:
>
>  > But, for some reason, the topic come up again and again from C++ devs
>  > that have no idea the optimization guys solved the issues for years now.
>
> If we are talking about C++, it is not possible to not take that copy
> for user-defined types. Due to separate compilation, the compiler does
> not even see the definition of operator++(int).
>
> And the compiler cannot replace calls to operator++(int) with calls to
> operator++() (when the return value is not used) because the programmer
> may have done different things than the canonical implmentation of
> post-increment.

Exactly. In C++, there isn't even a guarantee than an overloaded
postincrement operator is even related to an overloaded preincrement
operator. One could do addition while the other does subtraction - or
nothing at all. Sure, bad code won't do that, but the compiler doesn't know
whether you're being an idiot or not. So, it can't assume that overloaded
preincrement and postincrement are at all related and therefore can't
optimize a postincrement to a preincrement for overloaded operators.

The result is that simply always using preincrement when you need to
increment but don't specifically need to postincrement is a good habit to
get into. Its impact is likely to be minimal in most cases, but it doesn't
cost you anything, and you can't rely on the compiler's ability to optimize,
because the C++ standards committee didn't restrict the overloaded increment
(or decrement) operators enough to enable the compiler to optimize them
properly.

> C++ needs a rule like D's, which will never be there.

Yep. By making it so that you only overload a single operator for both
versions of increment, we avoid the whole problem in D, similar to how
having opCmp avoids bugs related to having to define each comparison
operator individually as is the case in C++.

It'll likely always bug me though when I see i++ when ++i would work, even
if it doesn't matter in D. It's just too ingrained in me, I guess. :)

- Jonathan M Davis




More information about the Digitalmars-d mailing list