"Semi-const" methods?

Jonathan M Davis jmdavisProg at gmx.com
Sun Mar 13 16:17:18 PDT 2011


On Sunday 13 March 2011 15:32:34 Magnus Lie Hetland wrote:
> On 2011-03-13 23:27:14 +0100, Magnus Lie Hetland said:
> > Any other ideas on how to handle this sort of "mostly const" or "const
> > where it counts" stuff? Perhaps my design intentions here are off to
> > begin with?-)
> 
> OK -- a *little* quick on the trigger there. My solution: Declare the
> method const, and assign the non-essential cache stuff to local
> variables, casting away the constness.
> 
> (Still open to schooling on the design part of this, though. Perhaps
> declaring a method as const is no good when it's not *really* const?
> For now, I'm just doing it to check that I don't inadvertently change
> things I don't want to change.)

What you want is logical const. You want it to be const from the perspective of 
an observer of the function but actually have stuff non-const within it. C++ has 
the mutable keyword to handle this. It's also completely legal and well-defined 
to cast away constness in C++. D, on the other hand, does not technically 
support logical const at all. It has to do with the complete lack of compiler 
guaranteeds.

You _can_ cast away constness in D, but it's breaking the type system when you 
do. It is perfectly valid for the compiler to assume that you function really is 
const and optimize appropriately. So, if you don't actually manage to _really_ 
be logically const, or if you do this with an immutable object (which would 
likely result in a segfault), you _are_ going to have incorrect code. On the 
whole, I'd advise just not using const when you need logical const, but if 
you're _very_ careful, you can get away with it. But thanks to immutable, it can 
be _very_ dangerous to cast away constness in a const function unless you're 
_very_ careful.

You really should check out this question on stackoverflow and the answers that 
go with it: http://stackoverflow.com/questions/4219600/logical-const-in-d

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list