我有一个“MyClass”类,它包含一些存储在 std::map
中的数据。标准 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 的 const_iterator
周围公开一个增强 transform_iterator
。转换函数应该是这样的
[](const pair<int, object*>& x)
{
return make_pair(x.first, const_cast<const object*>(x.second));
}
关于c++ - 通过只读迭代器公开成员数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7610283/