Pure delegate not quite pure?
Tofu Ninja via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Jul 1 13:32:02 PDT 2015
On Wednesday, 1 July 2015 at 12:34:35 UTC, Steven Schveighoffer
wrote:
> immutable is probably incorrect without a cast, since immutable
> cannot be applied implicitly to non-immutable data, and if the
> data is all immutable already, no sense in tagging it immutable.
>
> I really see use in allowing const.
>
> inout is sketchy, I'm trying to think of how this applies,
> since inout is really for data types that are varied in their
> constancy. A function has only one addressable instance.
>
> shared, well... I don't think we need it. Function stacks
> shouldn't be shared.
>
> One thing you CAN do as a workaround, is put all your data to
> return into a static struct, and return delegates that address
> your data:
>
> auto foo()
> {
> static struct Storage
> {
> int x = 4;
> pure int dg() immutable { return x * x;} // should be
> strong-pure
> }
> immutable(Storage) s;
> auto d = &s.dg; // I *think* this allocates a closure, but
> if not, that's a bug.
> writeln(d());
> // s.x = 5; // invalid
> return d;
> }
>
> Really, a delegate on a function stack is like a
> single-instance private-defined struct like written above.
>
> -Steve
The benefit of tagging it immutable would be to require the
delegate to always have an immutable context, for instance, I am
accepting a delegate as an argument to a function, but currently
right now I have no way to guarantee that the context i receive
is immutable. If it was marked immutable, then the supplier of
the delegate would be forced to use only immutable things in the
context. That's the primary benefit I see.
ie: void doSomethingWithDelegate(int delegate() pure @nogc @safe
nothrow immutable del)
That actually compiles, but it will only accept delegates to
member functions. ._.
I dont really know enough about shared and inout to comment on if
they could be useful, I only mentioned them because you can put
them on member functions.
More information about the Digitalmars-d-learn
mailing list