Boost logo

Boost Users :

From: Jon Biggar (yg-boost-users_at_[hidden])
Date: 2003-07-26 15:28:10


Joshua wrote:
> I've been reading through posts on here and in the docs but I think I
> may have missed something. Heres what I am trying to do: lets say I
> have a class Foo* and I'm trying to use it in a
> std::vector<shared_ptr<Foo> >. I can add them all day long and it
> works fine. The problem is that when I try to remove the shared_ptr
> from the vector. I expected it to delete the memory for the Foo* then
> delete itself (to completely free the memory that the shared_ptr used
> and the memory that the Foo was using. I think this is not happening
> though since the destructor is not being called when the elements are
> removed from the vector. Heres how I am currently inserting the
> shared_ptr's into the vector (yes I know this is the wrong way now
> that I've read a few of the posts here):
>
> typedef std::vector<boost::shared_ptr<Foo> > FooVector;
>
> FooVector Foobar;
> Foo* blah = new Foo();
> boost::shared_ptr<Foo> *> NewPointer = new boost::shared_ptr<Foo>(blah);
> Foobar.insert(*NewPointer); //Yes I know this looks horrible. And its probably wrong.

Yes, that's your mistake. You don't need to do a new of a shared_ptr<>,
and you are leaking that memory anyway, which means you are losing one
of the references to the shared object.

Your code can simply look like this:

typedef std::vector<boost::shared_ptr<Foo> > FooVector;
FooVector Foobar
boost::shared_ptr<Foo> NewPointer(new Foo());
Foobar.insert(NewPointer);

-- 
Jon Biggar
Floorboard Software
jon_at_[hidden]
jon_at_[hidden]

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