【发布时间】:2013-07-02 20:34:41
【问题描述】:
我有以下问题,不知道有没有更好的解决方法:
class myObj {
public:
typedef std::shared_ptr<myObj> handle;
typedef std::shared_ptr<const myObj> const_handle;
int someMethod() { ... }
int someConstMethod() const { ... }
};
现在我需要一个容器类,它允许您根据自己的constness 修改或读取myObj 的集合,如下所示:
class myCollection {
public:
typedef std::list<myObj::handle> objList;
typedef std::list<myObj::const_handle> const_objList;
inline objList& modify() { return _obl; }
// it would be nice to do this, but it won't compile as
// objList and const_objList are completely different types
inline const_objList& read() const { return _obl; } // doh! compile error...
// returning a const objList won't help either as it would return non-const
// handles, obviously.
// so I am forced to do this, which sucks as i have to create a new list and copy
void read(const_objList &l) {
std::for_each(
_obl.begin(),
_obl.end(),
[&l] (myObj::handle &h) { l.push_back(h); }
// ok as handle can be cast to const_handle
); // for_each
}
private:
objList _obl;
};
所以这个解决方案实际上是作为const myCollection 工作的,它只允许你获取const_handle 的列表,它只允许你调用myObj 的非修改方法(好)。
问题是“read”方法真的很丑(不好)。
另一种方法是以某种方式公开list 方法并返回const_handle 并根据需要进行处理,但这会产生很多开销,特别是如果您想使用比列表更复杂的东西。
有什么想法吗?
【问题讨论】:
-
可能
std::list不是正确的容器,因为它很少是正确的容器。std::list比std::vector更好的情况比较少见,更罕见的是它优于std::vector和std::deque的情况。 -
列表的getter/setter怎么样,即提供一个接口来改变列表而不是返回它?如果您只需要更改元素(不删除或插入),迭代器是另一种方式。
标签: c++ c++11 stl constants shared-ptr