I'm using Boost/shared_ptr pointers throughout my application. When the last reference to an object is released, shared_ptr will delete the object for me. The objects in the application subscribes to events in a central location of the application, similar to the observer/subscriber pattern.
In the object destructors, the object will unsubscribe itself from the list of subscriptions. The list of subscriptions is essentially just a list<weak_ptr<MyObject> >
. What I want to do is something similar to this:
Type::~Type()
{
Subscriptions::Instance()->Remove(shared_from_this());
}
My problem here is that shared_from_this cannot be called in destructors so the above code will throw an exception.
In my old implementation, the subscription list was just a list of pointers and then it worked. But I want to use weak_ptr references instead to reduce the risk of me screwing up memory by manual memory management.
Since I rely on shared_ptr to do object deletion, there's no single place in my code where I can logically place a call to Unsubscribe.
Any ideas on what to do in this situation?