D does have head const (but maybe it shouldn't)

Paul Backus snarwin at gmail.com
Tue Dec 29 19:25:38 UTC 2020


On Tuesday, 29 December 2020 at 17:56:51 UTC, H. S. Teoh wrote:
> I don't see why this is considered head const, nor why this 
> should be considered a bug. In the proposed solution `y` is not 
> a value type but a delegate that wraps the reference to *x.  
> Since x itself is non-const, this is perfectly valid, and the 
> `const` in `const y` refers to the immutability of the delegate 
> reference, not to the immutability of the wrapped reference.

It's a bug because `const` should apply transitively to both the 
delegate's function pointer and its context pointer. The easiest 
way to see this is to replace the delegate with a hand-written 
closure struct:

struct Closure
{
     int* p;
     this(inout int* p) pure @safe inout { this.p = p; }
     void opCall() pure @safe { *p = 2; }
}

auto f(int* p) pure @safe
{
     return Closure(p);
}

void g(const Closure y) pure @safe
{
     y();
}

In this version, `g` will fail to compile, because it is trying 
to call a mutable method using a const object.


More information about the Digitalmars-d mailing list