This is more a disussion than a question, but still.. A few days ago I found myself having a big problem in my program. I'll try and be brief with the situation I encountered. My plan was to have a callback function being executed every time a certain key, let's say space, was RELEASED. It had a few parameters, however the most important one was a pointer to some object, in that case it was an entity object for my game. That entity was stored in a vector as an unique_ptr, hence the memory was cleared up for me when I deleted that space in the vector.
Good enough, right? Well, the problem was that if that certain entity was deleted from memory, and right in the next tick of the program I released the space key, that callback function was executed with a pointer to that deleted entity. Silly as I was, I thought that pointer was going to magically turn itself to nullptr, hence not continuing the flow of the callback, "I did check if the pointer was null in the beginning of the function, and return if it was indeed null."
As you can imagine, the pointer was not null even after that entity was deleted. It pointed to some garbage azz trash memory that no one cared about. Eventually, I came across weak_ptr, changed the unique_ptr to a shared_ptr in the vector, and passed the entity as a weak_ptr instead of raw pointer to my callback. Finally, I checked if the weak_ptr was nullptr with the "lock()" function, which worked pretty neat for me. If the memory was deleted, that lock() would return null, and if not, it would return a shared_ptr inside my function.
You see, the reason I didn't want to use shared instead of unique was that I didn't want any class to "own" my entity. I wanted my entity to be destroyed as soon as either the vector goes out of scope or it's cleared. Nevertheless, that single ownership can be achieved with shared_ptr IF we pass pointers as a weak_ptr, so no other class will "own" my entity. In conclusion, std::weak_ptr is acually a good solution.
Now my question - is there a solution for dangling pointers other the weak_ptr? (Yes, I had set that unique_ptr to nullptr right before deleting the vector. But it did not change anything. The dangling pointer still pointed to some garbage memory.)