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.
I know that it’s possible to say delete this in C++ whenever you allocated
Share
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 doubledelete when last
shared_ptrdies. The only solution I can offer is “rethink your design” (you probably don’t needshared_ptrin the first place, and missiles probably could be values or pooled objects).