Logical const

Jonathan M Davis jmdavisProg at gmx.com
Wed Dec 1 10:26:24 PST 2010


On Wednesday, December 01, 2010 06:17:56 spir wrote:
> On Wed, 1 Dec 2010 03:22:39 -0800
> 
> Jonathan M Davis <jmdavisProg at gmx.com> wrote:
> > > 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.
> 
> Right, but isn't this the main point of Unqual!? (Would unqualify immutable
> as well, no?).

No. All Unqual does is help you with template constraints and static ifs. It 
doesn't actually change the type. In the function itself, you're still going to 
end up with a mutable, const, or immutable type to deal with. Unqual!T just 
makes it so that you don't have to check for every combination of const, 
immutable, shared, etc.

> > 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.
> 
> For this case, I prefere the "in" qualifier. (And imo value parameters
> should be "in" by default). Unless I miss important use cases, seems I
> would be happy with "immutable" and "in".

"in" _is_ const. It's essentially an alias for const scope.

Also, a classic example for the use of const which immutable doesn't help you 
with it all is returning member variables by reference or which are reference 
types when you don't want the caller to be able to modify them. Without const, 
you couldn't do that. const is huge. I'd _hate_ to see const go. The fact that D 
has const is one of the best things that it has going for it IMHO. I _hate_ the 
fact that languages like Java don't. It drives me nuts. Sure, you _can_ write 
programs without const - people do it all the time - but you have far fewer 
guarantees about your code, and it's much harder to determine which a function 
may or may not alter the value of a variable when you call it.

- Jonathan M Davis


More information about the Digitalmars-d mailing list