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:
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++.
In C pointers can be set to a value NULL which means, the pointer is not yet set or invalid. Any other value other than NULL means a valid pointer pointing to a proper memory location.
But of course it is a good practice to set the pointer to NULL/nullptr after deleting as the pointer location is invalid after deletion.
std::weak_ptr models temporary ownership: when an object needs to be accessed only if it exists, and it may be deleted at any time by someone else, std::weak_ptr is used to track the object, and it is converted to std::shared_ptr to assume temporary ownership.
It is always a good practice to assign the pointer NULL to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer.
You can use the lock()
member of boost::weak_ptr
to be able to test (then use) the value of the weak_ptr
without dealing with exceptions.
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