There is a constant class method that is often called. I decided to cache its results, so that if the class parameters have not changed, it will return the cached value, otherwise it will be re-read. However, this violates the constancy of the method, although nothing changes for the class user. What is the best way to do this in order to cache and not lose constancy? Can somehow change the class architecture?
Here's how I imagine it:
class A { int cached_value; int parameter; bool is_value_cached = false; public: void set_parameter(int x) { parameter = x; is_value_cached = false; } int foo() const { // const error if (!is_value_cached) { // ...compute value according to parameter... cached_value = 42; // assign value to cached_value is_value_cached = true; } return cached_value; } };
constqualifier, if it can change the state of the object? As an alternative, you can try to write an external cacher, in which there will be something like a type parameter -> cached_value. This will by the way be useful when you have several instances of the class, or the parameter values ββin them can be repeated. - VTTconstcorrectness is preserved, because this class is further used in constant methods, etc. - stevenis_value_cached- take out the public getter. And you make a method likerecalc()non-constant and blocking object. Then you can make a wrapper class, which will first call theis_value_cachedobject youis_value_cached, and then, depending on the state ofrecalc()andget_cached_value(). Even everything seems to be wrapped in a nice template :) - goldstar_labs