处理C ++类中的延迟计算 [英] Dealing with lazy computation in C++ classes
问题描述
假设我有一个类:
class NumberCollection
{
public:
typedef std::set<int> SetType;
typedef SetType::iterator iterator;
void insert(int n);
iterator begin();
iterator end();
size_t size() const;
iterator difficultBegin();
iterator difficultEnd();
size_t difficultSize() const;
private:
SetType easySet_, difficultSet_;
}
其中 insert()
向 easySet _
添加一个元素。 difficultSet _
的成员会根据 easySet _
的成员而变化。
Where insert()
adds an element to easySet_
. difficultSet_
's members change depending on the members of easySet_
.
我遇到的问题是,多次插入意味着 difficultSet _
不断重新计算。所以我想要 difficultSet _
懒惰地计算(即,只有当 difficultBegin()
, difficultEnd ()
或 difficultySize()
)。问题是,我实际上必须将 difficultSet _
变成 mutable
,因为否则 difficultSize )
无法操作它。
The problem I am having is that, multiple insertions means that difficultSet_
is constantly recalculated. So I want difficultSet_
to be calculated lazily (i.e., only when difficultBegin()
, difficultEnd()
, or difficultSize()
are called). The problem is, then I actually have to make difficultSet_
into a mutable
because otherwise difficultSize()
cannot operate on it.
现在我的类声明看起来像
So now my class declaration looks like
class NumberCollection
{
public:
typedef std::set<int> SetType;
typedef SetType::iterator iterator;
void insert(int n);
iterator begin();
iterator end();
size_t size() const;
iterator difficultBegin();
iterator difficultEnd();
size_t difficultSize() const;
private:
SetType easySet_;
mutable SetType difficultSet_;
mutable bool upToDate_;
}
我觉得这是不好的设计。有更好的方法吗?
I feel like this is bad design though. Is there a better way?
推荐答案
这是完全的方式。 const可以意味着二进制const,或者它可以意味着概念上的const。使用mutable意味着你在做更晚的事情,这是好的。
That's totally the way to do it. Const can mean binary const, or it can mean conceptually const. Using mutable means you're doing the later, which is fine.
这篇关于处理C ++类中的延迟计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!