The Status of Const

Jonathan M Davis jmdavisprog at gmail.com
Thu Aug 12 19:52:36 PDT 2010


On Thursday 12 August 2010 18:57:26 Michel Fortin wrote:
> Const-correctness can't work the same in D as in C/C++. Even if you had
> a mutable member in your class, D can't allow you to modify this member
> from a const member function, because this const member function can be
> called when your class is immutable, and if the class is immutable it
> can be shared across threads, in which case modifying the member
> (without synchronization) would cause races. Basically, D const system
> isn't build for const-correctness or to enforce what logically looks
> like const, it's built to ease concurrency and sharing of data between
> threads. All this to say that when something is const, it *is* const
> and it can't cause races.

That is, unfortunately, a very good point. It's still seriously limiting, 
however. What it means is that there is going to be code out there (and possibly 
a lot of it) which _should_ be const but can't be.

I confess that the more that I deal with immutable, the less I like it. const 
doesn't complicate things all that much and brings a lot of improvements. 
immutable complicates things quite a lot more and does not bring the same level 
of improvements to the table. However, it does help with multi-threaded apps 
which _is_ very important, and increasingly so, so it's probably better to have 
it than not. Still, it can be very frustrating. However, if there's a better way 
to do it, it'll likely be found with either a future version of D or a language 
which replaces D. There's a shortage of languages which have tried to mix const, 
mutable, and immutable together (D may be the only one actually), so there isn't 
much experience to base improvements on. And is usually the case, it's much 
easier to see the problems than their solutions.

- Jonathan M Davis


More information about the Digitalmars-d mailing list