Why D const is annoying

Jonathan M Davis jmdavisProg at gmx.com
Tue May 1 21:23:18 PDT 2012

On Tuesday, May 01, 2012 21:05:11 Mehrdad wrote:
> Okay, so let's say you're right
>     void process1(Student s) { .. }
>     void process2(const(Student) s) { ... }
> and that what I  guess what I REALLY want is to say, "process1() won't
> change the student's name, birthday, or any other attribute, but process2()
> will".
> How do you propose I make that guarantee known to the compiler/caller?
> Is that not the entire point of saying "const(Student)" in the first place?

Yes. And if you mark it as const, then the compiler will guarantee it. But 
with something like lazy loading, the object _does_ change. In D, const 
actually guarantees that a const object will not be altered, whereas C++'s 
doesn't. If you have an object which you don't intend to _logically_ alter but 
which whose state may change due to lazy loading, then the compiler can't give 
you any real guarantees anyway without having a lazy-loading mechanism of some 
sort built into the language.

In C++, the compiler can't use it to provide any real guarantees, because the 
programmer is free to violate const at any time via mutable or casting away 
const. Walter thinks that this makes C++'s const utterly useless (his focus is 
very much on what the compiler can and can't guarantee). Most of the rest of 
us disagree (it _does_ at least stop the programmer from inadvertently 
mutating a const variable directly), but with Walter's take on it, there's no 
way that he would have made D's const the same. And C++'s const just doesn't 
provide the kind of guarantees that D requires anyway, since the fact that a 
const object could actually be immutable makes it so that you can't safely 
cast away const to mutate anything, regardless of whether the compiler assumes 
that const objects never get altered.

The lack of logical const in D can be very annoying for some use cases, but 
the fact that D's const is guaranteed then makes it much better for other use 
cases. It's a tradeoff.

If all you want is something which indicates that you don't intend to alter 
the logical state of a variable (but you may alter its state in other ways - 
e.g. its cache), then D's compiler can't help you with that. Not even C++'s 
compiler really does much for that, since its const can be circumvented so 
easily. It just helps prevent you from doing it accidentally.

- Jonathan M Davis

More information about the Digitalmars-d mailing list