Sign in to follow this  
Grain

Like a smart pointer, but not.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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!!!!

Share this post


Link to post
Share on other sites
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.


Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this