Re: I'd like to use STL algorithms
Dan McLeran wrote:
This approach calls for undefined behavior in the current
C++ standard, because binary_op is not allow to cause any
side effects (in this case, incrementing count is a side
effect).
I didn't use a binary functor, I used a unary functor. I also
don't agree that incrementing an internal counter of a
function object is a side effect of calling transform with a
unary functor.
Who cares? There is no guarantee concerning the order in which
transform visits the elements of the sequence; on a modern,
multicore machine, it may even visit them in parallel. And
there isn't the slightest guarantee with regards to when and how
many times your operator is copied; an implementation could make
a new copy each time it uses it, for example.
In general, counting on mutable state in any functional object
used by the standard algorithms is playing with fire. At the
very least, you need to use some sort of indirection, so that
all copies of the object access the same state. And only in
exceptional cases, where the standard makes an explicit
guarantee, can you count on order being repected. (Two cases
where there is an explicit guarantee are for_each and
accumulate.)
--
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]