Why D const is annoying

Jonathan M Davis jmdavisProg at gmx.com
Tue May 1 23:30:29 PDT 2012


On Tuesday, May 01, 2012 23:14:06 Mehrdad wrote:
> > 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.
> 
> Maybe I'm being stupid, but how is the case any different in D?

D's type system assumes that const cannot be altered. As such, the compiler is 
free to optimize or alter its code generation based on that fact and any code 
which _does_ alter a variable after casting away const is breaking the type 
system and risking bugs. As far as the compiler is concerned, you _cannot_ 
alter a const variable through that variable (though another one might - 
unlike immutable - meaning that there are times when the compiler can't know 
that a const variable hasn't been mutated; it often can, however, particularly 
within a single function).

C++ specifically allows for const variables to be altered - either via mutable 
or casting away const. It _guarantees_ that it work to do so. And since it 
considers it completely legal to alter a const variable by either of those 
means, it _cannot_ assume that a const variable hasn't been altered except in 
very restricted circumstances. So, in general, the _only_ guarantee that C++'s 
const gives you is that you a const variable will not be altered save by 
casting away const or by one of its member variables being mutable.

So, it all comes down to what the compiler is free to assume and therefore 
guarantee. With D's type system, it's free to assume that you can never alter 
a const variable, so it guarantees that and any attempt to subvert that breaks 
the type system and whatever guarantees it gives you, risking bugs. With C++'s 
type system, it assumes that const _can_ be mutated via casting or mutable and 
guarantees that that will work, whereas it then _cannot_ assume that a const 
variable doesn't get mutated.

- Jonathan M Davis


More information about the Digitalmars-d mailing list