Export item data via read-only Iterator

I have a MyClass class that contains some data stored in std::map s. Standard maps contain pointers to objects, for example.

 private: std::map<int,Object*> m_data; 

I want to show data in the outside world, but I do not want other classes / functions to be able to modify (i) the m_data map or (ii) the objects that the values ​​in m_data . I would like to get some hypothetical function, say getDataBegin() , which returns an iterator over data having properties above. For example, I want the following pseudo-code examples not to execute:

 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. 

In short, you can say that I get read-only access to some member data. This is generally possible in a good way, and if so, how can I do this?

+4
source share
2 answers

Try to expose the transform_iterator boost wrapped around the const_iterator map. The conversion function should be something like

 [](const pair<int, object*>& x) { return make_pair(x.first, const_cast<const object*>(x.second)); } 
+2
source

returns const_iterator, const_iterator allows read-only access.

 std::map<int,Object*>::const_iterator const getDataBegin(); 
0
source

All Articles