FAQ 33.06 Which is better, i or i ?

FAQ 33.06 Which is better, ++i or i++?

++i is better unless the old value of i is needed.

The expression i++ usually returns a copy of the old state of i. This requires that an unnecessary copy be created, as well as an unnecessary destruction of that copy. For built-in types (for example, int), the optimizer can eliminate the extra copies, but for user-defined (class) types, the compiler retains the extra constructor and destructor.

If the old value of i is needed, i++ may be appropriate; but if it's going to be discarded, ++i makes more sense. Here's an example.

 #include <iostream> using namespace std; class Number { public:   Number() throw();  ~Number() throw();   Number(const Number& n) throw();   Number& operator= (const Number& n) throw();   Number& operator++ () throw();   Number  operator++ (int) throw(); }; Number::Number() throw()   { } Number::~Number() throw()   { cout << "dtor "; } Number::Number(const Number& n) throw()   { cout << "copy "; } Number& Number::operator= (const Number& n) throw()   { cout << "assign "; return *this; } Number& Number::operator++ () throw()   { cout << "increment "; return *this; } Number Number::operator++ (int) throw() {   Number old = *this;   ++(*this);   return old; } int main() {   Number n;   cout << "++n: ";  ++n;  cout << '\n';   cout << "n++: ";  n++;  cout << '\n'; } 

The output of this program follows.

 ++n: increment n++: copy increment copy dtor dtor dtor 

The postfix increment creates two copies of the Number the local object inside Number::operator++(int) and the return value of the same (a smarter compiler would notice that the returned object is always the local variable old, thus avoiding one of the two temporary copies). The final output line is the destruction of main()'s n.

Note that the postfix increment operator, Number::operator++(int), can be made to return void rather than the Number's former state. This puts the performance of n++ on a par with ++n but forfeits the ability to use n++ in an expression.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net