Boost logo

Boost :

From: Joe Gottman (jgottman_at_[hidden])
Date: 2002-06-10 19:20:35


    I still prefer the canonical way of doing postfix increment, because it
is more maintainable. No matter how the class is changed, as long as the
class has a copy constructor and a prefix increment, the canonical method of
postfix increment will be correct.

    Compare this to your new implementation. If the programmer ever changes
the implementation of the copy constructor, he must also remember to change
the private constructor that takes the postfix_increment object, or else he
will introduce a subtle bug. It's too bad that there is no way for a
constructor to call another constructor. If your private constructor could
call the copy constructor then your implementation would be maintainable.

Joe Gottman

----- Original Message -----
From: "Brad King" <brad.king_at_[hidden]>
To: <boost_at_[hidden]>
Sent: Monday, June 10, 2002 5:45 PM
Subject: [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;
> };
>
>


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk