Read only delegate

Edwin van Leeuwen via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Apr 4 04:19:19 PDT 2016


On Monday, 4 April 2016 at 08:10:10 UTC, Edwin van Leeuwen wrote:
> Is there a way to make sure a delegate only reads state, 
> without changing it? I tried annotating the delegate as const, 
> but that does not seem to work.
>

Note that annotating with pure also doesn't help. As a result we 
can have a pure delegate that returns different results every 
time it is called.

```D
void main()
{
     import std.stdio : writeln;
     auto r = [0,1,2,3];

     auto f = delegate() const pure
     {
         import std.array : front, popFront;
         r.popFront;
         return r.front;
     };

     r.writeln; // [0,1,2,3]
     auto f1 = f();
     r.writeln; // [1,2,3]
     assert( f() == f1 ); // Throws
}
```



More information about the Digitalmars-d-learn mailing list