I have a central repository of objects Base which can produce various things. Base must keep a pointer to all objects, as a central update method has to iterate through all objects created by the Base instance. However, if the last handle to an object is destroyed, there is no need to keep it around any more so Base should get somehow informed that it is ok to delete the object now. Manual deletion of objects should be also possible, which would immediately invalidate all handles. Some code to clarify:
Base* b = new Base;
auto h0 = b->MakeFoo ();
auto h1 = h0;
b->Delete (h0);
// h1 is invalid here
{
auto h2 = b->MakeFoo ();
}
// Base::Delete (h2) was called, as the last reference to it died
// shared_ptr/weak_ptr won't work here, as there would be still one
// reference in Base
auto h3 = b->MakeFoo ();
delete b;
// h3 is invalid here, hence shared_ptr is not enough
// weak_ptr would work here
Anything ready-to-use out there that I can adopt for this? Performance does not matter too much in this case.
How about this: Your class
Baseoutputsshared_ptrs through theMake*functions, but only storesweak_ptrs internally. The update loop can check whether the weak pointer is still valid and remove it if not.Your final requirement that deleting the base will also kill existing objects is a bit trickier. You could go through the weak pointers in
Base‘s destructor and send a self-destruct signal to all live objects, but that wouldn’t stop existing shared pointers.