When answering another question, it occurred to me that I maybe optimize some of my own older code that has err.. ‘less than optimal’ lifetime management.
I have at least one app where access/lifetime an object is controlled with a shared_ptr. This ptr is dynamically allocated so that it can be ‘atomically’ swapped out for another *shared_ptr, (and hence an updated object managed by the new ptr), without any locking. This seems to work fine, but I deliberately leak the old ptr because I don’t know when the last thread is going to be finished with it.
It occured to me now that I could, (maybe), delete() the old *shared_ptr in the dtor of the old object being managed. I would load the *sharedPtr into a private data member of the managed object upon creation so that the dtor could delete it.
Has anyone done this, or have any views on why it might be unsafe? I could try it, but I’m worried that, like so many multithreaded ‘optimizations’ it might just ‘appear to work’ until after I delivered it 🙁
It sounds like you have a bad design issue in your code more than anything else. First off, why would you want to create a
shared_ptr*? That already seems wrong.Then leaking it because you don’t know when other threads will be finished with it? What?? That’s bad.
Why not just have two
shared_ptrand use them properly? Maybe that will make your life much easier.Also, NO, you cannot get the
shared_ptr*to delete itself with the destructor of the object it owns. That would probably get into an unbreakable cycle. Because the shared_ptr is trying to delete the object it owns, and then that will try to delete the owner, which in turn…. You get the idea… That is silly.