Why D const is annoying

Jonathan M Davis jmdavisProg at gmx.com
Tue May 1 20:32:39 PDT 2012


On Tuesday, May 01, 2012 20:22:40 Mehrdad wrote:
> 1. Wouldn't your solution
>    (a) Be telling the programmer, "you *can't* lazy-load const objects"?
>    (b) Require duplicating the code 3 times? (Yes, you can factor it out as
> a mixin, but who wants to do that??)
> 
> 2. "Some folks that like lazy loading such as this seem to have come to the
> conclusion that they should just pretty much never use const, because it's
> too restrictive for they want to do."
> 
> Yes, that's **exactly** why I've said 'const is broken' for at least a year
> now, but it seemed like people objected to my conclusion...
> 
> The trouble, as I just showed, is that it isn't.
> "Lazy-loading" and caching aren't exactly obscure or rarely-used concepts --
> which seems to be the way they are portrayed here. They are *bound* to be
> used in any nontrivial program.
> So, if D doesn't let you use those techniques without 'hacking around' the
> language, then it doesn't matter how awesome D is otherwise -- C++
> programmers _simply won't_ switch to D, and other programmers will
> definitely have trouble using const, immutable, shared, etc...
> 
> In other words, my point with this entire thread was:
> These issues need to get *fixed* at some point on the _theory_ side. Who
> cares if the implementation takes an extra year or two to be finished? If
> it's wrong in theory, it's never going to be right in practice.

D's const does exactly what it intends to do. Yes, that means that lazy 
loading and const are mutually exclusive. And I don't expect that that will 
ever change. To change it would be to make it so that const isn't guaranteed 
to be const. There is _zero_ chance of convincing Walter of anything of the 
sort, and many in the community will back him in that. In order for the 
compiler to give solid guarantees, it can't be any other way, and more 
importantly, the fact that we have immutable means that it can't be any other 
way. If that means that you can't use const in many situations (even if you 
might use it in those same situations in C++), then that means that you can't 
use const. D's const is not C++'s const and was never intended to be.

> And it looks to me like there is no real clean 'fix' for this issue in D...
> the only solutions are along the lines of using C-style casts in C++ to
> throw-away const-ness, and we all know that isn't an actual solution...

It's worse than not an actual solution. It breaks the type system, throwing 
away the gurantees that the compiler gives you (easily resulting in bugs if 
you actually do it) and risks segfaults and the like if the underlying object 
is actually immutable.

- Jonathan M Davis


More information about the Digitalmars-d mailing list