How is chunkBy supposed to behave on copy

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Mar 20 22:11:49 UTC 2020


On Fri, Mar 20, 2020 at 03:59:57PM -0600, Jonathan M Davis via Digitalmars-d wrote:
> On Wednesday, March 18, 2020 10:29:53 AM MDT H. S. Teoh via Digitalmars-d 
> wrote:
[...]
> > 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.

Yes, that's right.  Actually, for by-value ranges the act of passing
them as an argument to a range function in the first place already
copies them.  The catch is really that once this happens, the caller or
whoever retains the original copy should no longer assume that the range
remains in the same place as before.  For some ranges this is true, but
for other ranges this assumption is invalid, and will lead to incorrect
results.


> 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.
[...]

+1.


T

-- 
Knowledge is that area of ignorance that we arrange and classify. -- Ambrose Bierce


More information about the Digitalmars-d mailing list