我有一个类“MyClass”,其中包含一些存储在 std::map
中的数据。标准映射包含指向对象的指针,例如
private:
std::map<int,Object*> m_data;
我想向外界公开数据,但我不希望其他类/函数能够修改 (i) map
m_data
或 (ii) m_data
中的值所指向的对象。我想要一些假设的函数,比如 getDataBegin()
,它返回一个迭代器,遍历具有上述属性的数据。例如,我希望以下伪代码示例失败:iterator_type itr = myclass.getDataBegin();
erase(itr); // not allowed because we cannot modify m_data;
itr.second = NULL; // not allowed to change content of m_data (falls under first rule)
itr.second->methodWithSideEffect(); // not allowed because changes content of object pointed to.
简而言之,您可以说我是在对某些成员数据进行只读访问。这完全有可能以一种很好的方式实现,如果是这样,我该怎么做呢?
最佳答案
尝试公开环绕 map transform_iterator
的 boost const_iterator
。变换函数应该是这样的
[](const pair<int, object*>& x)
{
return make_pair(x.first, const_cast<const object*>(x.second));
}