shared_ptr puzzle
I'm using ACE framework, but I'll try to describe my problem without referencing to it.
I have an event handler (class derived from ACE_Event_Handler). Reference to the event handler is hold by some manager class in maps of shared_ptr's.
At some point of time I want to:
- remove the event handler from manager map
- Some method of event handler should be called by 3rd class which holds row pointer to the event handler (for those familiar with ACE it's handle_close() called by ACE Reactor)
The problem is that order (1) and (2) is not promised. If (1) is called before (2), (2) will work on dangling event handler.
So I thought about adding some additional reference to event handler that will be decremented in (2).
How it can be done? Can the refere开发者_如何学JAVAnce to event handler be maintained from within the event handler itself (probably using enable_shared_from_this)?
Thanks
Holding shared pointer to itself in member variable will defeat purpose of shared_ptr, because you will need to inform in some way object about that it is not needed anymore (this is what "delete obj" for, which we trying to avoid using smart pointers).
As one of solutions: replace raw pointer in 3rd class by shared_ptr (or weak_ptr) if it is possible.
Other solutions depends heavily on design of your application, as example you can in some way force order for removing pointers from manager...
Try to investigate this document http://www.boost.org/doc/libs/1_43_0/libs/smart_ptr/sp_techniques.html, maybe you will find something usefull for you.
精彩评论