D constness: head & tail

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Mar 2 01:16:05 PST 2015


On Monday, March 02, 2015 11:21:32 drug via Digitalmars-d-learn wrote:
> what is the state of head&tail constness in D? Where we are and where we
> are moving toward?
> Where can I find some info about head and tail constness? I mean forum
> posts, stackoverflow questions, arcticles somewhere and so on.

There is no head-const in D. const is transitive, so you can never have
anything which is const with anything mutable inside it (other references to
the same data might refer to it as mutable, but never via any const
reference or pointer). However, tail-const is sometimes possible. For
instance, when slicing arrays, you get a tail-const slice (the resulting
array is mutable, but the elements themselves are still const). For
pointers, it's simply a matter of where you put the parens.

const T* foo;
const(T*) foo

both declare a const pointer to a const T, whereas

const(T)* foo

declares a mutable pointer to a const T. But something like

T const(*) foo;

is illegal, becaues it would violate the transivity of const.

For classes, we have std.typecons.Rebindable
(http://dlang.org/phobos/std_typecons.html#Rebindable):

Rebindable!(const T) foo;

Because there is no way to represent a class object separately from its
reference in D, there is no way to indicate that a reference should be
mutable while the class object itself is const, but Rebindable takes care of
that by using a wrapper struct so that the reference can still be const, but
the wrapper itself isn't.

There are mutiple places in the online documentation which discuss const,
e.g.

http://dlang.org/const3.html
http://dlang.org/const-faq.html

There are also several questions on stackoverflow which discuss it. A good
one to look at would be

http://stackoverflow.com/questions/4219600/logical-const-in-d

I also expect that Ali's book discusses it, but I'd have to go digging
through it to find it, and you'd probably be better served reading through
it yourself anyway:

http://ddili.org/ders/d.en/index.html

In any case, AFAIK, where we are with const will be where we will always be
with const in D. It's not something that's generally considered to need more
work. There are some folks who would like to see a way to do Rebindable
built into the language, but that's never happened, and I don't really
expect it to. But other than that, there really hasn't been much discussion
on changing how const works any time recently. So, "where we're moving
toward" is pretty much where we are now.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list