D does have head const (but maybe it shouldn't)
Petar
Petar
Tue Dec 29 17:13:48 UTC 2020
On Tuesday, 29 December 2020 at 16:15:56 UTC, ag0aep6g wrote:
> Exercise: Consider the following `main` function. Define `f`
> and `g` so that the code is valid, compiles, and runs
> successfully. The asserts must be executed and they must pass.
>
> ----
> void main() pure @safe
> {
> int* x = new int;
> const y = f(x);
> *x = 1;
> g(y);
> assert(*x == 2);
> }
> ----
>
> Hints:
> * You can't store `x` in a global because the code is `pure`.
> * You can't cast `const` away in `g` because that would be
> invalid.
> * You're supposed to find a type for which `const` means head
> const.
>
> Solution: https://run.dlang.io/is/dsaGFS
>
> 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.
More information about the Digitalmars-d
mailing list