Classification: |
C++ |
Category: |
Development |
Created: |
01/19/2001 |
Modified: |
06/12/2001 |
Number: |
FAQ-0556 |
Platform: |
Not Applicable |
|
Question: Why is it better to use the Pre-Increment Operator (e.g. ++var) rather than the Post-Increment Operator (e.g. var++)?
Answer: In C++ terms, if a copy constructor has been defined for the class you are incrementing, then using the post-increment operator
requires the creation of a temporary object. Looking at things in more detail, here are the steps performed by each operator:
pre-increment: *this += 1; return( *this ); post-increment: Object temp = *this; ++(*this); return( temp ); Hence the pre-increment operator just increments and returns, whilst the post-increment operator has to take a copy, increment
the object and return the un-incremented copy. So for C++, the post-increment operator needs to construct and destruct a new
object in order to return the un-incremented value. It is therefore more efficient to use the pre-increment operator rather
than the post-increment operator.
In EPOC terms, if the class being incremented is a T or R class there is a small saving (the bitwise copy of the class into
a temporary). As for C classes, you will need to use the pre-increment operator as you're not allowed copy constructors on
C classes. Symbian coding standards recommend using the pre-increment operator wherever possible, so that you get into the habit of it,
and are more likely to use it automatically in situations where it actually makes a difference.
|