Getting the const-correctness of Object sorted once and for all

Chad J chadjoan at __spam.is.bad__gmail.com
Tue May 15 14:17:45 PDT 2012


On 05/15/2012 03:32 PM, Chris Cain wrote:
> On Tuesday, 15 May 2012 at 18:07:12 UTC, Chad J wrote:
>> An idea I thought of is to introduce a method local declaration that
>> allows a method to access instance-specific-state that isn't
>> accessible to the rest of the class:
>
> This is an interesting idea (as it seems to really try to keep
> the state changes internal to the function, which can be seen as
> how D handles purity)... however, it breaks the point of purity due to
> this:
>
> pure nothrow hash_t toHash() const {
> @instance hash_t bad = 0;
> ++bad;
> return hashfn(field) + bad;
> }
>
> Now it violates everyone's definition of purity and we can no
> longer make our sweet optimizations and reasoning about the code.
> Sure, we could "trust the programmers to not do this" ... but
> that's another debate entirely.


Yes.  I intend to "trust the programmers to not do this".

Otherwise we need to find some way to ensure that a function that alters 
external state will always return the same value as long as the rest of 
the program doesn't change the state it looks at.

>
>> To communicate intents to invalidate the cache:
>>
>> class Foo
>> {
>> private toStringCacheValid = false;
>>
>> public void methodThatInvalidatesCache()
>> {
>> ...
>> toStringCacheValid = false;
>> }
>>
>> public pure nothrow string toString() const
>> {
>> // strCache gets stored in an instance of Foo
>> // strCache is only accessable in this method body.
>> @instance string strCache = null;
>>
>> if ( !toStringCacheValid )
>> {
>> // Observable change in strCache!
>> // ... because isCaching reveals it
>> // to everyone.
>> strCache = someComplicatedCalculation();
>> toStringCacheValid = true;
>> return strCache;
>> }
>> else
>> return strCache;
>> }
>> }
>
> ... and setting toStringCacheValid to true in toString violates
> const, so this is absolutely not allowed. Sorry.
>

Yep, ya got me.

>
> Maybe there's a solution, but I doubt the solution is something
> the programmer can/should do completely transparently.
>


More information about the Digitalmars-d mailing list