called copy constructor in foreach with ref on Range

Jonathan M Davis newsgroup.d at jmdavisprog.com
Mon Jun 22 20:51:37 UTC 2020


On Monday, June 22, 2020 1:41:34 PM MDT kinke via Digitalmars-d-learn wrote:
> On Monday, 22 June 2020 at 19:03:44 UTC, Jonathan M Davis wrote:
> > in practice, that means that generic code cannot use a range
> > once it's been copied
>
> Translating to a simple rule-of-thumb: never copy a (struct)
> range, always move.

You're unlikely to find much range-based code that does that and there
really isn't much point in doing that. Again, copying isn't the problem.
It's using the original after making the copy that's the problem. And moving
doesn't fix anything, since the original variable is still there (just in
its init state, which would still be invalid to use in generic code and
could outright crash in some cases if you tried to use it - e.g. if it were
a class reference, since it would then be null). So, code that does a move
could accidentally use the original range after the move and have bugs just
like code that copies the range has bugs if the original is used after the
copy has been made. So, the rule of thumb is not that you should avoid
copying ranges. It's that once you've copied a range, you should then use
only the copy and not the original.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list