D does have head const (but maybe it shouldn't)
ag0aep6g
anonymous at example.com
Tue Dec 29 16:15:56 UTC 2020
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>).
More information about the Digitalmars-d
mailing list