2

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:

  • If the item is in use, don't do anything, and delete it later
  • If the item is not in use, delete it

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:

  • Would this respect the desired behavior ?
  • Does the 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

Rippalka
  • 380
  • 6
  • 16
  • 2
    `std::list >` remove/erase functions cause deletion of the real object *only if that was the last shared_ptr referencing the object*. Which is exactly what you say you want. I'm guessing that you are using shared_ptr and normal pointers to the same object. The answer is simple, don't do that, shared_ptrs only and it will work as you say you want it to. Sometimes I wonder at the ability of newbies to make life difficult for themselves. – john Oct 20 '12 at 08:46
  • Thanks for the answer. Well, what you said is what I thought. I was getting double frees in my program (that is quite big) and with `valgrind` assumed I was doing it wrong. I tried to reproduce it in a small program and couldn't. I guess I'm a newbie like you said. Thanks for the help – Rippalka Oct 20 '12 at 09:34

1 Answers1

4

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.

matthias krull
  • 4,389
  • 3
  • 34
  • 54
alestanis
  • 21,519
  • 4
  • 48
  • 67