Let's not make invariants const

Jonathan M Davis jmdavisProg at gmx.com
Sat Aug 4 00:15:35 PDT 2012


On Saturday, August 04, 2012 09:06:19 Era Scarecrow wrote:
>   As mentioned before, doesn't 'const' _only_ apply to the current
> (this) object and not anything else? Besides the contracts can't
> have lasting side effects that would change logical execution.
> How would changing the current object in an invariant be correct
> in release code?

The problem is that if the this pointer/reference is const, then you can't 
call any member functions which aren't const, and you can't call any non-const 
functions on any member variables, because _they're_ const, because the this 
pointer/reference is const. And there are plenty of types out there which 
_can't_ have many of their member functions be const and do what they need to 
do, because D's const is both physical and transitive (unlike C++'s const). 
So, it's quite easy to get into a situation, where you can't call much of any 
functions at all if the this pointer/reference is const even though calling 
the non-const functions wouldn't actually mutate anything.

- Jonathan M Davis


More information about the Digitalmars-d mailing list