This SO question sparked a discussion about std::generate
and the guarantees made by the standard. In particular, can you use function objects with internal state and rely on generate(it1, it2, gen)
to call gen()
, store the result in *it
, call gen()
again, store in *(it + 1)
etc., or can it start at the back, for example?
The standard (n3337, §25.3.7/1) says this:
Effects: The first algorithm invokes the function object gen
and assigns the return value of gen through all the iterators in the range [first,last)
. The second algorithm invokes the function object gen and assigns the return value of gen through all the iterators in the range [first,first + n)
if n
is positive, otherwise it does nothing.
It seems like no ordering is guaranteed, especially since other paragraphs have stronger wording, for example std::for_each
(Effects: Applies f
to the result of dereferencing every iterator in the range [first,last)
, starting from first and proceeding to last - 1
. If we're taking this literally, it only guarantees to start at first
and end at last
though - no guarantees on the ordering in between).
But: Both Microsoft's and Apache's C++ standard library both give examples on their documentation pages that require the evaluation to be sequential. And both libc++ (in algorithm
) and libstdc++ (in bits/stl_algo.h
) implement it that way. Moreover, you lose a lot of potential applications for generate
without this guarantee.
Does the current wording imply sequentiality? If not, was this an oversight by the members of the committee or intentional?
(I am well aware that there aren't many people who can provide insightful answers to this question without merely speculating or discussing, but in my humble opinion, this does not make this question 'not constructive' as per SO guidelines.)
Thanks to @juanchopanza for pointing out this issue and referring me to the paragraph about for_each
.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…