gpt4 book ai didi

c++ - 缓存方法结果时如何处理常量?

转载 作者:行者123 更新时间:2023-12-05 00:43:04 30 4
gpt4 key购买 nike

我有一个带有方法(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;
}

我正在寻找类似 RefCell 的东西在锈中。

最佳答案

这是 mutable 的情况之一specifier特别适合。当类(class)成员是 mutable ,即使封闭类是 const,也可以更改该成员.

所以,如果 MyClass::cachedValuemutable Foo*而不是 Foo* , 你可以有 const MyClass 中的成员函数对 cachedValue 进行更改然后所有调用代码都可以作用于 const MyClass正常。

关于c++ - 缓存方法结果时如何处理常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71540734/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com