Why D const is annoying

Jonathan M Davis jmdavisProg at gmx.com
Tue May 1 23:37:48 PDT 2012


On Tuesday, May 01, 2012 23:10:04 Mehrdad wrote:
> "Chris Cain"  wrote in message news:nqgwunggifrgmwwhkcql at forum.dlang.org...
> 
> > What about the object do you want const? How should this object normally
> > change things? It looks like the way you've coded it, your connection will
> > get information off of a server.
> 
> I don't think you answered my question.
> 
> What I said (or meant to ask) was this:
> - OK, FINE, let's say I don't know what D's const() means, then. Maybe it
> isn't suitable for what I need. I just want to know:
>   _How do you specify that the function process1() won't modify its
> 'student' parameter_?

What you're thinking about here is logical const. You want a way to indicate 
that an object is not logically altered by the function that you're passing it 
to. With logical const, the inner state of the object _can_ change so long as 
the state of the object as seen from the outside is constante.

However, D's const is _physical_ const. It guarantees that the object isn't 
altered _at all_. And that _is_ part of the interface, because no non-const 
function can be called on a const object, and every const function statically 
guarantees that it doesn't mutate the object that it's on.

There is _no_ way in D to indicate that an object won't be altered by a 
function save for guaranteeing that it won't be altered _at all_ by using 
const. There is no way to indicate that it won't be altered logically save for 
comments.

And in reality, having the compiler verify that an object's logical state 
doesn't change even when some of its internal state does is _very_ difficult (if 
not impossible) to statically verify. As such, the compiler can make no such 
guarantees. Not even C++ does that. Arguably, C++'s const is a glorified 
comment. Walter certainly sees it that way and doesn't think that there is 
_any_ value to C++'s const as a result. What it _does_ guarantee is that you 
won't accidentally alter the object (since you have to cast away const to 
alter it, or some of its member variables are going to have to be mutable), so 
I'd argue that it's still very useful. But it does _not_ actually guarantee 
that the object won't get mutated by that function. It's effectively just a 
comment which the compiler partially verifies.

It would be _very_ cool to be able to have a compiler-checked, logical const, 
but it probably isn't realistically possible, except maybe in very restrictive 
circumstances.

- Jonathan M Davis


More information about the Digitalmars-d mailing list