samedi 19 mars 2022

How to deal with constness when the method result is cached?

I have a class with a method (getter) that performs some relatively expensive operation, so I want to cache its result. Calling the method does not change behavior of the object, but it needs to store its result in this, so it can't be const.

The problem is that I now have another method that is const and I need to invoke my getter. Is there some generally accepted solution to this problem? Should I bypass the constness checking in the getter to make it const, (Coudn't that cause problems with optimizing compiler?) or I have to propagate the non-constness to all methods that use this getter?

Example:

class MyClass
{
public:
    Foo &expensiveGetter() /*const?*/
    {
        if (cachedValue == nullptr) {
            cachedValue = computeTheValue();
        }
        return *cachedValue;
    }

    void myMethod() /* How to make this const? */
    {
        auto &foo = expensiveGetter();
        // etc.
    }

private:
    Foo *cachedValue = nullptr;
}

I am looking for something like the RefCell in Rust.

Aucun commentaire:

Enregistrer un commentaire