Issue with forward ranges which are reference types
Jonathan M Davis
jmdavisProg at gmx.com
Wed Aug 17 01:12:27 PDT 2011
On Wednesday, August 17, 2011 09:03:52 Peter Alexander wrote:
> On 17/08/11 5:05 AM, Jonathan M Davis wrote:
> > It was previously determined that this would be a problem for ranges
> > which are reference types (classes in particular, but it affects
> > structs as well, if copying them doesn't create an independent range).
> > So, we added the save property.
> >
> > <snip>
> >
> > Thoughts?
>
> Apologies for my ignorance, but I haven't really been following all this
> ranges stuff.
>
> I must be missing something, why would you ever expect an algorithm that
> works with value types to work with reference types as well?
A range is any type which has the appropriate functions on it. It doesn't
matter whether it's an array, a struct, or a class. And if it's a struct, it
could be either a value type or a reference type. So, a range could be either
a value type or a reference type. In the general case, you can't know without
reading the code whether a particular range is a value type or a reference
type (though obviously in the case of classes, you know that it's a reference
type), and traits can't tell you whether a range is a value type or a
reference type. So, range-based functions can't assume that a range is a value
type, and they can't assume that a range is a reference type. This has nothing
to do with the elements in the range mind you. It's purely a matter of the
type of the range itself.
So, in order to deal with the issue that
auto rangeCopy = range;
doesn't necessarily copy, save was introduced to make it so that you can
guarantee that you're getting a copy
auto rangeCopy = range.save;
The issue that I'm bringing up is that you still get different behavior between
value type and reference type ranges when you pass them to a function. The
only way to guarantee the same behavior is to either call save before passing
a range into a function or to call it once it's been passed in.
In any case, essentially what it comes down to is that you have no idea in the
general case whether a range is a value type or a range type, and you _have_
to code in a manner which works with both or you're going to end up with buggy
code.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list