On 2008-01-25 17:27, Lionel B wrote:
Generally you can not make such an assumption, no. With a good
compiler and with no weird implementations of the ++ operator
you might, but unless you check the code generated for each
usage you can never be sure.
Use the copy in any way. Use the copy in the postfix increment
operator, for example, something like:
T
operator++( T& obj, int )
{
T result( obj ) ;
operator++( obj ) ;
result.dump( std::cout ) ; // outputs internal state...
return result ;
}
It's easy to invent cases where postfix would be slower. The
fact is that they don't occur in practice. To begin with, the
copy must be fast and efficient to begin with, since the STL
copies iterators like crazy anyway. And the things you do to
make it fast and efficient (e.g. like keeping the internal state
simple, and making the copy constructor inline) help the
compiler in optimizing it.
I've posted this several times before, but I carefully
benchmarked loops with prefix and postfix increment, for all of
the standard iterators, using g++, and there was no difference.
One thing that did make a difference (although not a large one)
was moving the call to end() out of the loop:
for ( Iter i = c.begin(), e = c.end() ; i != e ; i ++ ) {
}
turns out to be measurably faster than:
for ( Iter i = c.begin() ; i != c.end() ; ++ i ) {
}
in fact. But the difference is always small enough that it
would be foolish and a waste of time to even think about it
(until the profiler says otherwise, of course).