I know that it's possible to say delete this
in C++ whenever you allocated something with new
, using traditional pointers. In fact, I also know that it's good practice IF you handle it carefully. Can I have an object say delete this
if it's being held by an std::shared_ptr
? And that ought to call the destructor, right? To give you an idea, I'm making a game where a ship can shoot missiles, and I'd like to have the missiles delete themselves.
the last remaining shared_ptr owning the object is destroyed. the last remaining shared_ptr owning the object is assigned another pointer via operator= or reset().
All the instances point to the same object, and share access to one "control block" that increments and decrements the reference count whenever a new shared_ptr is added, goes out of scope, or is reset. When the reference count reaches zero, the control block deletes the memory resource and itself.
No, it's not safe, the lifetime of the object is determined by holders of shared_ptr
, so the object itself cannot decide whether it wants to die or not. If you do that, you'll get double
delete when last shared_ptr
dies. The only solution I can offer is "rethink your design" (you probably don't need shared_ptr
in the first place, and missiles probably could be values or pooled objects).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With