Reputation: 380
I have a question related to boost::shared_ptr<>
in C++. I am currently willing to perform a smart deletion of the items of my list:
This is a behavior required by my program.
I am really wondering how to do that properly since the std::list<boost::shared_ptr<object> >
remove/erase functions causes the deletion of the shared_ptr<>
and therefore of the real object.
So I finally came up with this solution: use a std::list<object*>
and inherit object
from boost::enable_shared_from_this<>
. That way, when someone needs to use an item from the list, I give them object->shared_from_this()
.
My questions are the following:
boost::shared_ptr<>
associated to shared_from_this()
takes into consideration the reference to the object in the list ?I hope my question is explicit enough and that someone will be able to help me. The proper use of the smart pointers in lists is something I'd like to be able to use.
Thank you
Upvotes: 2
Views: 3382
Reputation: 21863
When you delete a shared_ptr
you don't delete the real object unless it is not used anywhere else. That's the whole point about using shared_ptr
.
For instance, if you take one element of the list, copy it and give it to another function, then delete the element from the list, the real object won't be deleted because it is still referenced somewhere else.
Upvotes: 4