|
Boost : |
From: Brad King (brad.king_at_[hidden])
Date: 2002-06-10 16:45:29
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