Range Redesign: Copy Semantics

Steven Schveighoffer schveiguy at gmail.com
Tue Jan 23 17:25:47 UTC 2024


On Monday, 22 January 2024 at 17:18:56 UTC, Paul Backus wrote:
> On Monday, 22 January 2024 at 15:41:35 UTC, Atila Neves wrote:
>> I think that `.save` was a historical mistake, and that ranges 
>> that can be copied are forward ranges. Something like a range 
>> reading from stdin or a socket would/should disable the 
>> copy/postblit constructors.
>
> This was my initial thought too, but it turns out it's not 
> quite that simple.
>
> If we *require* basic input ranges to be non-copyable, then 
> types which are inherently copyable (in particular, `T[]`) will 
> be exclude from being basic input ranges.

You are thinking about this the wrong way. Copyability becomes a 
trait of forward ranges, instead of input ranges. An input range 
would not be copyable, therefore code which takes input ranges 
would have to take them by reference, or the caller would have to 
ensure no other copies exist. But you can still take forward 
ranges this way.

It is not hard to do -- you just remove the requirement for 
copying from `isInputRange`, and add it to `isForwardRange`.


> In order to use a `T[]` with an algorithm that expects a basic 
> input range, you would have to wrap it in a `struct` that has 
> copying disabled.

A `T[]` can be used without copying it. So why can't you pass 
that into an algorithm that takes an input range?

> It's also a big problem for composability. If half the 
> algorithms require your range to be copyable, and the other 
> half require it to be non-copyable, you have to keep track of 
> [what color each algorithm is][1] whenever you write a range 
> pipeline, or write a new algorithm that calls an existing one 
> internally.

The assertion is that if the range is copyable, it's now a 
forward range and copying is allowed. It is *on you* as the range 
developer to ensure copying does not work if it's an input range. 
The algorithm that says `isInputRange` would have to avoid 
copying, but that also works for forward ranges as well. There 
would be no need for multiple colors.

Now, in *practical* terms, algorithms that are input-range 
compatible likely would need more careful attention to avoid 
copies than they currently do.

-Steve


More information about the Digitalmars-d mailing list