
Originally Posted by
Deimos
It's true that there's no reason not to do it, but there's also really no reason TO do it. Any decent compiler will compile it down to the same thing when it realizes you're not using the value of the variable anyway. Regardless, even if the compiler doesn't fix it, if you're really trying to optimize your program at that miniscule of a level you probably shouldn't be writing it in a high level language.
This is not entirely true. It probably is in Java, but in C++ it definitely isn't. In C++ you can overload the ++ operator on an object, and then you can say ++object, or object++. This is extremely common with iterators in the STL, for example. How many times have you seen code like this?
Code:
for (Iterator iter = container.begin(); iter != container.end(); iter++)
{
T i = *iter;
}
This is awful! It is not possible to perform any optimizations on the call to iter++, because the compiler uses a different function to implement iter++ and ++iter. It must call the appropriate function, and in the postvix version, an actual copy of the object is made, because that's what you need to return from the function - the value before "incrementing". Depending on the implementation of your constructor, this copy might perform expensive operations. Even if it doesn't, you're still allocating extra memory which although quite fast is still unnecessary. In the implementation of the prefix operator, you don't need to copy anything. You just increment the stuff and return *this.
In any case, many people build their applications with all optimizations off, and in that case the prefix version will outperform the postfix version even on basic data types like int. If nothing else though, I prefer the prefix just for consistency since sometimes it's "necessary".