Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shared_ptr: what's it used for

I make a lot of use of boost::scoped_ptr in my code and it is great but I'm currently working with software that uses shared_ptr all over the place and I'm wondering if I'm missing something.

AFAIK a shared_ptr is only useful if different threads are going to be accessing the same data and you don't know what order the threads are going to finish (with the shared_ptr ensuring that the object exists until the last thread has finished with it).

Are there other use cases?

like image 274
Patrick Avatar asked Nov 30 '22 12:11

Patrick


2 Answers

Threads are irrelevant here. What's relevant is whether it's easy to specify a point at which the object is no longer of use.

Suppose several different objects want to use the same object. It might be a pack of data, or for input/output, or some geometric object, or whatever. You want the shared object to be deleted after all of the using objects are deleted, and not a clock cycle before. Rather than figure out which owning object is going to have the longest lifespan (and that can change if you change the program, or perhaps through user interaction), you can use a shared_ptr to force this behavior.

It doesn't matter whether the using objects are in the same or different threads. Objects can have unpredictable lifetimes even if they're all in the same thread.

like image 139
David Thornley Avatar answered Dec 05 '22 07:12

David Thornley


AFAIK a shared_ptr is only useful if different threads are going to be accessing the same data

Well, it's for situations where multiple owners own the same object pointed to by the smart pointer. They may access the smart pointers from different threads, and shared_ptr is usable in that area too, but that's not the main point. If the last owner loses its reference to the object pointed to, the shared_ptr mechanism deletes the object.

You can use a scoped_ptr if all you want to have is a pointer that is deleted when the scope it's created in is left (either by exceptions, by a goto to a place outside, or by normal control flow or some other mechanism). If you use it like that, there is no need to change to shared_ptr.

like image 35
Johannes Schaub - litb Avatar answered Dec 05 '22 06:12

Johannes Schaub - litb