How is chunkBy supposed to behave on copy

Jonathan M Davis newsgroup.d at jmdavisprog.com
Fri Mar 20 21:59:57 UTC 2020


On Wednesday, March 18, 2020 10:29:53 AM MDT H. S. Teoh via Digitalmars-d 
wrote:
> 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.

Ranges get copied all the time when passing them around. You're not going to
avoid it (even using them with foreach copies them). The key thing is not
that a range shouldn't be copied without using save but that if a range is
ever copied, then the original shouldn't be used again, and from that point
on, only the copy should be used.

So, if you pass a range to foreach, a function, or do anything else which
would copy it, then don't use the original again, and if you want to use it
again, then instead of copying it directly, call save to get an independent
copy. Generic code should _never_ rely on the copying semantics of a range,
and even in non-generic code, depending on the semantics of copying a range
whose implementation you don't fully control is just begging for bugs.

- Jonathan M Davis





More information about the Digitalmars-d mailing list