jiw*_*ene 5 c++ getter design-patterns memoization
我有一个类,它的方法(getter)执行一些相对昂贵的操作,所以我想缓存它的结果。调用该方法不会改变对象的行为,但需要将其结果存储在 中this
,因此它不能是 const。
问题是我现在有另一个 const 方法,我需要调用我的 getter。这个问题有一些普遍接受的解决方案吗?我是否应该绕过 getter 中的 constness 检查以使其成为 const(这不会导致优化编译器出现问题吗?)或者我必须将非 constness 传播到使用此 getter 的所有方法?
例子:
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;
}
Run Code Online (Sandbox Code Playgroud)
我正在寻找类似RefCell
Rust 的东西。