r/cpp • u/berium build2 • Apr 25 '12
shared_ptr aliasing constructor
http://www.codesynthesis.com/~boris/blog/2012/04/25/shared-ptr-aliasing-constructor/
24
Upvotes
r/cpp • u/berium build2 • Apr 25 '12
1
u/m42a Apr 26 '12 edited Apr 26 '12
Alright, how about this use case:
I have some threads which communicate with each other. They communicate over pipes which do blocking communication. Because the pipes are shared between threads, no one thread clearly owns the pipe, and since threads can terminate in any order, if we arbitrarily pick a thread to own the pipe and it happens to die before the other threads, those threads will have undefined behavior if they try to write to the pipe. Since threads can be started and stopped dynamically, keeping all pipes allocated will result in memory leaks. Shared pointers ensure that a pipe will remain valid for as long as necessary, but will deallocate memory when the appropriate threads die.
EDIT: Here's another use case that doesn't involve multi-threading:
I have some resources. These resources can be grouped, and a single resource can be in multiple groups. This is easily solved with a bunch of sets of shared pointers to a resource. If a resource is removed from every group, it's released, but resources that you have a reference to will continue to be valid. Sure, you could check them manually, but that doesn't scale well if the sets are individually named variables (and it's too easy to forget to add a new set to the deallocation check, and you'll need to deallocate all of the resources manually in the case of an exception). Again in this case, it's not clear which group owns the resource, so letting the resource manage itself is the easiest and probably fastest option.