Is there a simple, efficient weak/guarded pointer? I need multiple pointers to the same object that are all automatically set to NULL when the object is deleted. There is one "master" pointer that is always used to delete the object, but there can be several other pointers that reference the same object.
Here are some solutions that don't quite match my needs:
- QPointer: I am not developing a QT app; I do not wish to include this libary/derive from QObject.
- boost::weak_ptr:
an exception is thrown when accessing a deallocated object. Too expensive for my situation: it should be normal to test a weak pointer; I plan to do some manual clean-up when a weak pointer is no longer valid.update:weak_ptr can be tested without throwing exceptions - Low-Overhead Weak Pointers: This is very close to what I am looking for, except I don't like the fact "This scheme is only guaranteed to work as long as you don’t allocate 2**sizeof(int) times in the same location."
Why I need these weak/guarded pointers: I have a game with a list of game objects. Some objects are dependent on others, for example a debug/stats object that is associated with a game entity. The debug/status object displays useful info about the game entity, but it only makes sense while the game entity exists. So if the game entity is deleted, the debug/stats object should realize this and delete itself. (Another idea is a tracking missile: instead of deleting itself, it may search for a new target.)
I wish to keep the debug/stats logic separate from the game entity. The game entity should not have to know a debug/stats object is attached to it. While I'd prefer an answer for weak/guarded pointers, I also welcome different ways to approach my specific task. I am thinking I may have to implement a game object manager that tracks object lifetimes and uses handles instead of raw pointers to memory addresses.
I am developing in C++.
std::weak_ptr
. Looks similar to the one from Boost. – Kurdistan