Like a smart pointer, but not.

Started by
4 comments, last by Nitage 17 years, 6 months ago
As I understand it when working with smart pointers an object is automatically deleted when all of the smart pointers pointing to it are destroyed. Is there the reverse of this? Meaning I can explicitly destroy an object and then all pointers to it, no matter where they are, will become null or are somehow made aware that the object was deleted. So that I don't accidentally refer to it again through one of those pointers. While typing this just now it occurs to me that this sounds a lot like the observer pattern, and I suppose I could implement it my self, but I don't want to reinvent the wheel if I don't have to.
Advertisement
Such a thing does indeed exist.

The Boost C++ libraries' implementation calls it a weak_ptr, and it is a "Non-owning observer of an object owned by shared_ptr", shared_ptr being your standard smart pointer.

Whether and how you use this "weak" smart pointer depends on your language and the needs of the situation.
{[JohnE, Chief Architect and Senior Programmer, Twilight Dragon Media{[+++{GCC/MinGW}+++{Code::Blocks IDE}+++{wxWidgets Cross-Platform Native UI Framework}+++
I have encountered many situations where I thought that having a pointer or pointers automatically reset would be extremely convenient. But specifically this time I had in mind game entities. Game entities in general can be deleted at almost any time for a multitude of different reason. And there are many things that may maintain pointers to a game entity including other entities. So when one is deleted it would make sense, it seams to me, to have any pointer to it automatically reset.
I am using Boost's weak_ptr for that exact same reason (managing entity references) and it is absolutely wonderful. You have like 0 maintainance code for keeping track of entity pointers, besides a quick check to see if the weak_ptr currently points to anything.

Use them now!!!!
OpenSceneGraph uses these kind of pointers, as an addition to their smart pointers, which they call observed pointers.

www.openscenegraph.org
You need to use 2 layers of indirection for this.

In other words, instead of storing an entity*, you can store an entity** - a pointer to an entity pointer. That way you can set the entity* pointed to to 0 when the entity is destroyed. As other people have pointed out, boost::weak_ptr wraps this idea in an easy to use manner.


This topic is closed to new replies.

Advertisement