1

Again reading C++ Primer 5 Edition. I am on chapter 12 Dynamic memory. Everything is OK. Until this point in the book:

"Because memory is not freed until the last shared_ptr goes away, it can be important to be sure that shared_ptrs don’t stay around after they are no longer needed.The program will execute correctly but may waste memory if you neglect to destroy shared_ptrs that the program does not need.One way that shared_ptrs might stay around after you need them is if you put shared_ptrs in a container and subsequently reorder the container so that you don’t need all the elements.You should be sure to erase shared_ptr elements once you no longer need those elements.

Note

If you put shared_ptrs in a container, and you subsequently need to use some, but not all, of the elements, remember to erase the elements you no longer need."

  • I don't understand this paragraph can someone explain to me how may shared_ptrs leaks? and an example of the "container" of shared_ptr that can cause leak. Thank you.
Itachi Uchiwa
  • 3,044
  • 12
  • 26
  • 1
    sounds similar to C++'s "erase-remove" idiom because `std::remove` doesn't actually remove elements, it just reorganizes them – kmdreko Oct 20 '19 at 00:36

1 Answers1

3

It essentially means that as long as you have a std::shared_ptr object in your container the object it points to will not be deleted.

So once you have no more use of that object, you should remove the corresponding std::shared_ptr from your container so the storage can be freed.

If you were to keep adding elements to your container and never removing any, you would essentially leak memory (ofc it will be cleaned up when the reference count hits 0, but until then it's reserved for no reason).


Side note, make sure you always think about when you are using std::shared_ptr. Often a std::unique_ptr is enough and should the need arise to make it shared it's easy to do that. See Does C++11 unique_ptr and shared_ptr able to convert to each other's type?

also

https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rr-unique

deW1
  • 5,562
  • 10
  • 38
  • 54
  • 1
    So you mean no real leak as long as they'll be destroyed when the container object is destroyed (getting out of scope)? – Itachi Uchiwa Oct 19 '19 at 23:15
  • 2
    Yes once the reference count hits 0 (there are no more shared_ptr instances of it), it will delete the object it points to. So worst case when the application exits. Better case when the container is destroyed and best case once you don't need it anymore by removing it from the container. – deW1 Oct 19 '19 at 23:21