Inherited const when you need to mutate

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Jul 10 15:13:59 PDT 2012


On Tue, Jul 10, 2012 at 11:59:48PM +0200, Jakob Ovrum wrote:
> On Tuesday, 10 July 2012 at 21:18:18 UTC, H. S. Teoh wrote:
> >If I'm OK with physical const, then all is fine and dandy.  But as
> >soon as one thing can't be const, I've to re-engineer my entire
> >framework from ground up.
> >
> >Isn't there something we can do to improve this situation?
> >
> >
> >T
> 
> I don't think the answer is to change D's const. D's const, unlike
> C++'s const, only exists to bridge immutable and mutable data. As
> soon as it becomes incompatible with immutable (which C++'s const
> very much is), it ceases to be purposeful.

I don't think we want to change physical (bitwise) const. It does have
its uses, and it's necessary if you want immutable to work nicely with
mutable. But if the current const is all we have, then IMO something is
missing from the language.


> The problem arises when const is forced upon interfaces like toString
> and opEquals. we don't expect these functions to change observable
> state. In other words, we expect them to be logically constant, but
> not necessarily bitwise constant. That's not something the compiler
> can enforce, and it shouldn't try to. Other operators, e.g. opIndex,
> correctly leave the responsibility to the programmer.

Exactly, that's what I mean, we're using bitwise const in druntime in
places where we actually intended _logical_ const. Bitwise const is a
subset of logical const, and right now the subset is the only thing we
have.


> There's also the reality that you want toString, opEquals, etc. to
> work with immutable (run-time type) class instances, requiring
> compatibility with const (compile-time type) references.
> 
> What I don't understand is why we've chosen const over mutable, when
> we should strive for allowing either and maybe even both. We've moved
> from one end of the scale to the opposite - our current situation is
> equally limiting to the previous situation.

I suppose the thought was that since const subsumes both mutable and
immutable, it would be the ideal middle ground.  But it turns out not to
be the case. (Or rather, it _is_ the case, just not quite what we'd
imagined.)


> I think these changes were rushed; understandable considering the
> amount of pressure, but it just fixes one problem and creates an
> equally big new problem.

I don't think they were rushed. There's been a push for making druntime
and Phobos const-correct for a while now. I don't think this change is a
_mistake_ per se, but it does expose a flaw in the language: const is
too limited in scope, and we need something else to fill in for use
cases where const isn't good enough.


T

-- 
Why have vacation when you can work?? -- EC


More information about the Digitalmars-d mailing list