rlb*_*ond 4 c++ const mutable lazy-evaluation
假设我有一节课:
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_;
}
Run Code Online (Sandbox Code Playgroud)
在哪里insert()添加元素easySet_.difficultSet_成员的变化取决于成员easySet_.
我遇到的问题是,多次插入意味着difficultSet_不断重新计算.所以我想difficultSet_将懒洋洋地计算(即,只有当difficultBegin(),difficultEnd()或者difficultSize()被称为).问题是,那么我实际上必须做成difficultSet_一个mutable因为否则difficultSize()无法操作它.
所以现在我的班级宣言看起来像
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_;
}
Run Code Online (Sandbox Code Playgroud)
我觉得这个设计很糟糕.有没有更好的办法?