Fully transitive const is not necessary

Steven Schveighoffer schveiguy at yahoo.com
Thu Apr 3 07:33:54 PDT 2008


"Janice Caron" wrote
> On 02/04/2008, Steven Schveighoffer wrote:
>> Absolutely, but I'd at least like Walter to stop saying that transitive
>>  const (read, transitive *keyword* const) is neccessary for pure 
>> functions :)
>>  If he says "Oh yeah, I guess transitive const isn't necessary, but it's 
>> not
>>  a priority to fix it right now", then I'd be happy.
>
> But hang on. It's all very well saying "pure functions can access the
> non-mutable bits only", but in every case I can think of where I might
> use the mutable keyword in C++, the non-mutable subset of the class is
> completely useless without the mutable subset.
>
> Can you give me a counterexample of a logically const (muty) class in
> which the non-mutable subset is actually useful?

Certainly:

class SuperIntensiveCalculator
{
    private mutable int[int] cache;

    int f(int x) const
    {
         int *result = x in cache;
         if(result !is null)
             return result;
         /* do really intense calculation, cache the value */
    }

    pure int puref(int x) invariant
    {
        /* do really intense calculation, do not use cache */
    }
}

If your instance is invariant, you can call puref, which doesn't use the 
cache, but allows the compiler to do it's own optimizations (and possibly 
memoization).

Yes, I could make cache just a normal member, and remove the const on f(x), 
but then I couldn't call f on const instances, which gives me less 
functionality.  I could also implement this in globby form, but then the 
lookup for the cache is going through 2 AA's, and I have to manually 
initialize and destroy the cache for each instance.

-Steve 





More information about the Digitalmars-d mailing list