How is chunkBy supposed to behave on copy
H. S. Teoh
hsteoh at quickfur.ath.cx
Wed Mar 18 16:29:53 UTC 2020
On Wed, Mar 18, 2020 at 02:57:41PM +0000, Dukc via Digitalmars-d wrote:
[...]
> This is how chunkBy[1] currently behaves when copying. It essentially
> behaves like a reference range: it will only save it's state when
> `save` is explicitly called, not otherwise, even if the chunked source
> range is a forward range with value semantics.
The current range API design, which Andrei himself admitted was not the
best design in retrospect, does not specify behaviour on copying a
range. IOW, it's the application-level equivalent of undefined
behaviour. Generally, this is not a problem because usually you're
working with your own range types which you already know the semantics
of. But in generic code, assumptions of this sort are a no-no,
precisely because of breakages of this sort when different ranges behave
differently on copy.
tl;dr: never copy a range directly, always use .save. Never assume a
range remains unchanged after iterating a copy; always assume the worst
and use .save whenever you wish the original range to remain unchanged
afterwards.
> As most Phobos ranges preserve the value semantics of their source
> ranges,
[...]
This is a dangerous assumption. My personal advice is, if you expect a
range to retain its contents after iteration, call .save explicitly.
Don't assume anything not explicitly required by the range API.
T
--
Verbing weirds language. -- Calvin (& Hobbes)
More information about the Digitalmars-d
mailing list