ASPN ActiveState Programmer Network
ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups


Recent Messages
List Archives
About the List
List Leaders
Subscription Options

View Subscriptions
Help

View by Topic
ActiveState
.NET Framework
Open Source
Perl
PHP
Python
Tcl
Web Services
XML & XSLT

View by Category
Database
General
SOAP
System Administration
Tools
User Interfaces
Web Programming
XML Programming


MyASPN >> Mail Archive >> boost
boost
[boost] Postfix Increment Operator
by Brad King other posts by this author
Jun 10 2002 9:45PM messages near this date
Re: [boost] Postfix Increment Operator | Re: [boost] Postfix Increment Operator
Hello, all:

The standard way I've seen to implement a postfix increment operator
looks like this:

 foo operator++(int) { foo temp(*this); ++(*this); return foo; }

This implementation is used by boost libraries in several places,
including the graph library and the iterator adaptors.

I've recently discovered a different way to implement the operator
that may give a performance improvement.  The example "number" class
shown below demonstrates the technique.

Basically, the operator is implemented using a special private
constructor that acts like a copy constructor, but increments the
original value when it is done.  This has the advantage of allowing
the compiler to implement the return value optimization since there is
no named temporary.

The technique is simple enough that I'm surprised I've never seen it
before.  If anyone has seen this technique elsewhere, please let me
know.

Thanks,
-Brad


class number {
private:
  class postfix_increment {};
  
  // Postfix increment operator implemented using this constructor.
  number(number& r, const postfix_increment&): value(r.value)
    {
    // Copy construct first, then increment original value.
    ++r;
    }
  
public:
  
  // Need non-private constructor for example.
  number(): value(0) {}
  
  // Standard prefix increment operator.
  number& operator++()
    {
    ++value;
    return *this;
    }
  
  // Postfix increment operator implemented using private constructor.
  const number operator++(int)
    {
    return number(*this, postfix_increment());
    }
  
private:  
  int value;
};


_______________________________________________
Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost
Thread:
Brad King
Mattias Flodin
Joe Gottman
David Abrahams

Privacy Policy | Email Opt-out | Feedback | Syndication
© ActiveState Software Inc. All rights reserved