Search code examples
c++11containersshared-ptr

C++ primer 5 edition: Container of shared_ptr


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.

Solution

  • 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