Fully transitive const is not necessary

Janice Caron caron800 at googlemail.com
Thu Apr 3 10:03:12 PDT 2008


On 03/04/2008, Steven Schveighoffer <schveiguy at yahoo.com> wrote:
> Have you no imagination? :)

Apparently.

So to cut a long story short, you're saying that you can have a class
in which a non-pure function caches a result (in a mutable variable),
and in which the pure version of the same function doesn't cache the
result.

You might just as well say, you can have a class in which a non-const
function caches a result, and in which the const version of the same
function doesn't. What's the difference?

I guess what I'm trying to get at is that it is never /necessary/ to
use mutable variables. There's always a way of rewriting the code so
you don't need them. In this case:

    class Calclulator
    {
        int config;
        int f(int x) const { ... }
        pure int f(int x) invariant { ... }
    }

    class CachingCalculator
    {
        Calculator calculator;
        int[int] cache;
        int f(int x)
        {
            auto p = x in cache;
            if (p !is null) return *p;
            int r = calculator.f(x);
            cache[x] = r;
            return r;
        }
    }

You just have to wean yourself off the addiction to logical const.
After you've gone cold turkey for a bit, you'll just stop wanting to
use it.



More information about the Digitalmars-d mailing list