Shared_ptr container, but iteration with raw pointers

I have a class that contains a list containing boost::shared_ptrs for objects of another class.

Class member functions that provide access to an element in a list return the original pointers. For consistency, I would also like to be able to iterate using raw pointers instead of shared_ptrs. So when I dereference the list iterator, I would like to get a raw pointer, not shared_ptr .

I assume that for this I need to write a custom iterator. It's right? If so, then someone can point me in the right direction - I have never done this before.

+6
source share
2 answers

The Boost transform_iterator option is used here:

 #include <list> #include <boost/iterator/transform_iterator.hpp> #include <tr1/memory> #include <tr1/functional> using std::list; using std::tr1::shared_ptr; using boost::transform_iterator; using boost::make_transform_iterator; using std::tr1::mem_fn; using std::tr1::function; struct Foo {}; struct Bar { typedef shared_ptr< Foo > Ptr; typedef list< Ptr > List; typedef function< Foo* (Ptr) > Functor; typedef transform_iterator< Functor, List::iterator > Iterator; Iterator begin() { return make_transform_iterator( fooptrs.begin(), mem_fn( &Ptr::get ) ); } Iterator end() { return make_transform_iterator( fooptrs.end(), mem_fn( &Ptr::get ) ); } List fooptrs; }; 

C ++ 11 will simplify the removal of the function shell, but I don't have a compiler that could test it. You can also hide a specific Iterator type using erase erase if you see the need (I think Adobe offers a free any_iterator class any_iterator for this purpose.)

+5
source

Sometimes I see people reach STL boost::shared_ptr containers, when in fact boost::ptr_container may be a less likely and less well-known choice.

This may or may not be one of these cases, but to consider that one of the nice ptr_container classes is that their iterators have an β€œextra” indirectness that helps keep it clean and safe.

+1
source

Source: https://habr.com/ru/post/912536/


All Articles