In D, how do I declare an either const or immutable pointer to non-const / mutable data in D?
The dlang website says you can't just declare it as const, as this makes both the pointer const and the data it points to is non-modifiable.
I've read earlier posts relating to this that suggest that it's simply impossible. If so, then that's a big hole in the language design. It should be possible to declare the pointer alone as non-modifiable, otherwise it's madness. Having the const propagate from pointer to also imply const data is possibly a useful default safety feature.
You don't. In D, const
, immutable
, and shared
are all transitive. So, once an outer part of the type is const
(or immutable
or shared
), the whole type is. At one point, very early in D2, the language had both head const
and tail const
, but it was deemed too complicated to be worth it, and it was removed (back in version 2.015 IIRC). So, now const
, immutable
, and shared
are fully transitive, and it's been that way for years.
You can declare stuff like
const(int)* p;
so that the inner portion of the type is const
, but there is no way to indicate that the outer portion is const
without making everything inside it const
as well.
So, yes, what you're trying to do is impossible in D, which is perhaps less flexible than might be ideal, but head const
is also hands down the least useful form of const
. So, while it might be a loss, as far as I can tell, it really isn't a big one. And allowing head const
would really complicate things - especially when immutable
and shared
came into play. So, the current system is much simpler without losing much power, making it arguably a very good tradeoff.
If you really wanted something like head const
, you could always create a wrapper type that disallowed assignment, but that's the closest that you're going to get.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With