Why D const is annoying

Jonathan M Davis jmdavisProg at gmx.com
Wed May 2 00:33:04 PDT 2012


On Wednesday, May 02, 2012 00:10:33 Mehrdad wrote:
> Whoa, what?
> 
> So you're saying
>      "X results in UB"
> means
>      "Compiler guarantees X"
> ?
> 
> 
> By that philosophy, C and C++ are orders of magnitude better than D, given
> how many so-called "guarantees" they make about your code...

I don't follow.

The D compiler guarantees that as long as you don't cast away const, const 
will never be mutated. If you _do_ cast away const and then mutate the 
variable, you are doing something which is undefined. As it is undefined 
behavior, _anything_ could happen if you do it, and the compiler is free to 
assume that it will never happen. So, it effectively has a guarantee that a 
const variable will never be mutated (save by another, mutable reference to 
the same data). It then uses that guarantee for optimizations.

To make it 100% iron-clan, casting away const would have to be illegal, but 
that would be unacceptable in a systems language - particularly when you want 
to be able to call C functions which may not be properly annotated. So 
instead, the compiler assumes that its guarantee holds in the case where you 
cast away const, and is still able to use it for optimizations.

C++ _does_ define what happens when you cast away const and mutate a variable, 
so it guarantees that that behavior will be safe. In so doing however, it is 
then unable to assume that casting away const will not result in the variable 
being mutated and is therefore unable to use const for much in the way of 
optimizations.

- Jonathan M Davis


P.S. You can check out this stackoverflow question on the subject as well:

http://stackoverflow.com/questions/4219600/logical-const-in-d



More information about the Digitalmars-d mailing list