Why D const is annoying

Jonathan M Davis jmdavisProg at gmx.com
Wed May 2 00:01:44 PDT 2012


On Tuesday, May 01, 2012 23:44:30 Mehrdad wrote:
> You said:
> "In C++, the compiler can't use it to provide any real **guarantees**..."
> 
> Now you're telling me D doesn't guarantee it either.
> And then go on telling me about how D uses const-ness to make assumptions
> and improve performance.
> 
> Isn't your answer orthogonal to your claim? o.O
> 
> Whether the compiler makes **GUARANTEES** about code is _irrelevant_ to
> whether or not the language uses 'const' to improve performance.

No, what the compiler guarantees is _very_ relevant to using const for 
improving performance. The _only_ reason that the compiler can use const for 
any kind of optimizations is because it can guarantee that the variable won't 
change. If it can't guarantee that, then it _cannot_ use const for 
optimizations. How could it? What would there be to optimize? Optimizations 
with const are based on the fact that the variable didn't change, so if the 
compiler can't guarantee that, how could it make any optimizations based on 
that?

And yes, D's type system _does_ guarantee that a const object doesn't change 
specifically because casting away const and mutating an object is _undefined_. 
It goes outside of the type system. You can do it, because D is a systems 
language, but the compiler is free to make optimizations based on the 
assumption that you will never mutate a const variable. So, the compiler _can_ 
make the guarantee that const isn't mutated, and if you do, you _will_ have 
bugs - just like if you did something screwy like casting an object no void* 
nad then casting it to a completely different type afterwards could cause bugs. 
You've thrown away the type system at that point, and it's up to the 
programmer to maintain the compiler's guarantee in such situations, or you'll 
get bugs, because the compiler relies on that guarantee.

C++, on the other hand, _does_ define what happens when you cast away const and 
mutate a variable, so its type system has to assume that a const variable 
_can_ change and therefore can rarely use it for optimizations (i.e. only in 
cases where it can statically verify that you _didn't_ cast away const and 
that not mutable variables are involved - which is likely to be rather rather, 
since even just making a function call would defeat it, since C++ doesn't do 
cross-function optimizations like that).

The difference here is in what the compiler considers to be defined or not and 
therefore what assumptions it's permitted to make.

- Jonathan M Davis


More information about the Digitalmars-d mailing list