Brandon
Brandon

Reputation: 493

Pointers to automatically null when object is deleted

Say I have an object and 10 pointers to it in several other objects of varying class types. if the object gets deleted, those pointers have to be set to null. normally I would interconnect the object's class with the classes which have pointers to it so that it can notify them it is being deleted, and they can set their pointers to null. but this also has the burden that the classes must also notify the object when THEY are deleted since the object will need a pointer to them as well. That way the object doesn't call dereference a dangling pointer when it destructs and attempts to notify the others.

I don't like this confusing web of crap and I'm looking for a better method.

Please note that auto pointers and shared pointers are not what I'm looking for - auto pointers delete their object when they destruct, and shared pointers do the same when no more shared pointers are pointing to it. What I'm looking for is a slick method for setting all pointers to an object to null when the object destructs.

Upvotes: 3

Views: 1098

Answers (2)

Stochastically
Stochastically

Reputation: 7846

Auto pointers and shared pointers etc are basically just classes that handle this kind of stuff for you. But it sounds like you've got a slightly different requirement, so I think you should develop your own class to manager pointers and use that instead of the raw pointers. That way you should be able to get the slick functionality that you're looking for.

Upvotes: 0

Ben Voigt
Ben Voigt

Reputation: 283694

"All problems in computer science can be solved by another level of indirection" -- David Wheeler

In your case, what will work very well is

std::shared_ptr<Object*> pp.

When you delete the object, set the shared Object* to null (e.g. *pp = 0;). All the other users are sharing the Object*, and will now see that it has become null. When all the users are gone, the memory used for the Object* itself will also be freed.

Upvotes: 9

Related Questions