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

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Dec 29 17:56:51 UTC 2020


On Tue, Dec 29, 2020 at 05:13:48PM +0000, Petar via Digitalmars-d wrote:
> On Tuesday, 29 December 2020 at 16:15:56 UTC, ag0aep6g wrote:
[...]
> > ----
> > void main() pure @safe
> > {
> >     int* x = new int;
> >     const y = f(x);
> >     *x = 1;
> >     g(y);
> >     assert(*x == 2);
> > }
> > ----
[...]
> > The validity of the given solution might be arguable, and I'd be in
> > favour of outlawing it. It's surprising that there's a type for
> > which `const` means head const when it means transitive const for
> > everything else. It's so surprising that even DMD trips over it
> > (<https://issues.dlang.org/show_bug.cgi?id=21511>).
> 
> Wow. The solution surprised me, even though in retrospect it's obvious
> to me why it works (bugs in this area of the type system have been
> know for more than a few years). I'd say head-const is a very useful
> tool, but it's pretty obvious to me that this shouldn't be a supported
> way to implement it.

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.


T

-- 
GEEK = Gatherer of Extremely Enlightening Knowledge


More information about the Digitalmars-d mailing list