Boost logo

Boost Users :

Subject: [Boost-users] shared_ptr and container iterators
From: Johannes Totz (johannes_at_[hidden])
Date: 2012-04-16 10:19:31


Hi all,

just started playing with boost::shared_ptr.
How do I get a const iterator pointing to a shared_ptr pointing to a
const object? See code below, I'd like to prevent a MyItem being changed
through const iterators.

struct MyItem
{
        int value;
};

struct MyContainer
{
        typedef std::set<boost::shared_ptr<MyItem> > MySet;
        MySet set;
};

int main(int argc, char* argv[])
{
        MyContainer mc;

        boost::shared_ptr<MyItem> p(new MyItem);
        p->value = 5;
        mc.set.insert(p);

        MyContainer::MySet::const_iterator i = mc.set.begin();
        // cannot mutate shared_ptr pointed to by iterator: ok
        //(*i).reset(new MyItem);
        // cannot change ptr but can change value: ok
        (*i)->value = 6;

        MyContainer::MySet::iterator j = mc.set.begin();
        (*j).reset(new MyItem);

        // how to do this?
        // should not change ptr nor MyItem
        std::set<boost::shared_ptr<const MyItem> >::const_iterator k =
mc.set.begin();

        return 0;
}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net