foreach() behavior on ranges
Steven Schveighoffer
schveiguy at gmail.com
Wed Aug 25 10:59:44 UTC 2021
On 8/25/21 6:06 AM, Joseph Rushton Wakeling wrote:
> On Tuesday, 24 August 2021 at 09:15:23 UTC, bauss wrote:
>> A range should be a struct always and thus its state is copied when
>> the foreach loop is created.
>
> That's quite a strong assumption, because its state might be a reference
> type, or it might not _have_ state in a meaningful sense -- consider an
> input range that wraps reading from a socket, or that just reads from
> `/dev/urandom`, for two examples.
>
> Deterministic copying per foreach loop is only guaranteed for forward
> ranges.
structs still provide a mechanism (postblit/copy ctor) to properly save
a forward range when copying, even if the guts need copying (unlike
classes). In general, I think it was a mistake to use `.save` as the
mechanism, as generally `.save` is equivalent to copying, so nobody does
it, and code works fine for most ranges.
What should have happened is that input-only ranges should not have been
copyable, and copying should have been the save mechanism. Then it
becomes way way more obvious what is happening. Yes, this means forgoing
classes as ranges.
-Steve
More information about the Digitalmars-d-learn
mailing list