Mutable ForwardRange save() method not callable using const object
Steven Schveighoffer
schveiguy at gmail.com
Tue Sep 4 14:26:44 UTC 2018
On 9/4/18 9:53 AM, Timoses wrote:
> Hey,
>
> I'm fiddling around with ranges a bit and am wondering why save is not
> callable on a const object:
...
> I could imagine that save is not marked as const because it is uncertain
> whether any indirections are part of the content..? But couldn't the
> compiler check that?
But you have eliminated any visibility into the range itself -- you
stuck it behind an interface.
> Could anybody explain what exactly is going on? Is there a reason the
> `save()` is not working on const objects?
The trivial reason is because the method is not marked const:
https://github.com/dlang/phobos/blob/master/std/range/interfaces.d#L153
The real reason is that given a const interface, everything inside it
must be const as well. Making a copy of that makes a const copy, which
by definition couldn't be assigned back to the original range (which is
likely not const).
At the very least, it should be inout. But in either case, the function
needs to be properly marked.
As general advice, I wouldn't expect const to work well with Ranges
anyway -- const ranges are useless (you can't iterate them). So not much
code is expecting to handle const, including the wrappers that Phobos
provides.
-Steve
More information about the Digitalmars-d-learn
mailing list