Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"delete this" to an object that's allocated with std::shared_ptr?

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.

like image 683
JesseTG Avatar asked Apr 22 '12 19:04

JesseTG


People also ask

Does shared_ptr delete?

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().

What happens when shared_ptr goes out of scope?

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.


1 Answers

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).

like image 112
Cat Plus Plus Avatar answered Oct 22 '22 16:10

Cat Plus Plus