Logical const

Jonathan M Davis jmdavisProg at gmx.com
Wed Dec 1 03:22:39 PST 2010


On Wednesday 01 December 2010 03:13:08 spir wrote:
> On Tue, 30 Nov 2010 15:03:43 -0800
> 
> Walter Bright <newshound2 at digitalmars.com> wrote:
> > Andrew Wiley wrote:
> > > I've been following this thread on and off, but is there a definition
> > > somewhere of exactly what "const" means in D2 and exactly what that
> > > guaranties or doesn't guaranty?
> > 
> > Const provides a read-only "view" of a reference and anything reachable
> > through that reference. It guarantees that no other thread can read or
> > write that reference or anything reachable through it.
> > 
> > It does not guarantee that there isn't a mutable alias to that reference
> > elsewhere in the same thread that may modify it.
> 
> What would be the consequences if D had no const, only immutable (that,
> IIUC, removes the latter non-guarantee)?

The biggest problem would be that no function could then work on both a mutable 
and an immutable value (unless it could be copied by value). With const, you can 
pass both mutable and immutable stuff to it. Without const, any and all functions 
which would want to deal with both would have to be duplicated. That includes 
stuff like member functions.

And of course, as C++ shows, there are plenty of cases where having const but no 
immutable can be quite valuable. Just the fact that you can pass an object to a 
function and know with reasonable certainty (and more certainty in D than C++) 
than that object won't be altered can be extremely valuable. Sure, many 
languages get by without const, but I think that they're definitely worse off for 
it. And with immutable added to the mix, I think that const is that much more 
important.

- Jonathan M Davis


More information about the Digitalmars-d mailing list