0

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:

  1. remove the event handler from manager map
  2. 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 reference to event handler be maintained from within the event handler itself (probably using enable_shared_from_this)?

Thanks

4

1 回答 1

1

在成员变量中持有指向自身的共享指针将破坏 shared_ptr 的目的,因为您需要以某种方式告知对象它不再需要(这就是“删除 obj”的目的,我们试图避免使用智能指针) .
作为解决方案之一:如果可能的话,用 shared_ptr(或weak_ptr)替换第 3 类中的原始指针。其他解决方案在很大程度上取决于您的应用程序的设计,例如,您可以以某种方式强制命令从管理器中删除指针...
尝试调查此文档http://www.boost.org/doc/libs/1_43_0/libs/ smart_ptr/sp_techniques.html,也许你会找到对你有用的东西。

于 2010-10-06T10:09:00.497 回答