why weak pointers don’t work

Recently, I’ve implemented a weak pointer class that manages its resource pointer by setting it to NULL in every instance that uses that same resource.

 

That way, weak pointers allow for notifying anyone who has a pointer to that resource once the resource gets deleted.

 

Good idea, especially since p407 uses a dynamic editor environment with objects that reference others that might get deleted at any point.

The problem

the weak pointer is implemented as a template class.

My object hierarchy allows me to instanciate an object of a certain type, then pass a pointer to that object to any method that accepts a pointer of a base class.

with weak pointers, that’s no longer possible.

You’d have to construct a weak pointer of type <base class> and pass that one to the function, effectively killing the whole benefit weak pointers give us.

 

the solution: cast operator

I would have to implement a cast method that allows me to cast a weak pointer of type T to one of type U while maintaining its ref-counter and pointer address.

Only the type of the object-pointer the address  points to would have to be changed.

 

conclusion

The effort of implementing such a cast operator is manageable, the  overhead for calling these cast operators every single time an object has to be accessed by its weak pointer however would be enormous and render the weak pointer idea completely impractical.

Ergo, weak pointers and p407 don’t mix.

 

the final solution

if any object, trigger and action path item were to be instanciated by its appropriate manager class, a slightly different approach could work:

the manager classes store pointers to the created objects and return references to those pointers.

path items and their child classes store not the pointers themselves but the references to those pointers.

If one items were to request the deletion of one of the objects, each reference to that pointer would then point to NULL, fulfilling the functionality of a weak pointer while keeping polymorphism intact.

 

In order to achieve that, each path item constructor (or c’tors of its descendants) have to be privatized and made accessible by the manager classes only.

One thought on “why weak pointers don’t work

  1. the “final solution” turns out to be as impractical as weak pointers themselves: no default-arguments, no non-const to const conversion, etc.

    double-pointers would probably work, with similar restrictions but they’re very inconvenient.

    I’ve decided to let the whole concept go and implement a different mechanism to check whether pointers to path items are valid.

Leave a Reply