共享指针谜题
我正在使用 ACE 框架,但我会尝试在不引用它的情况下描述我的问题。
我有一个事件处理程序(从 ACE_Event_Handler 派生的类)。 对事件处理程序的引用由shared_ptr 映射中的某个管理器类保存。
在某个时间点,我想要:
- 从管理器映射中删除事件处理程序
- 事件处理程序的某些方法应该由第三个类调用,该类保存指向事件处理程序的行指针(对于熟悉 ACE 的人来说,它是由 ACE Reactor 调用的 handle_close() )
问题是订单(1)和(2)没有得到承诺。如果 (1) 在 (2) 之前调用,则 (2) 将作用于悬空事件处理程序。
因此,我考虑添加一些对事件处理程序的额外引用,这些引用将在 (2) 中递减。
怎样才能做到呢? 是否可以从事件处理程序本身内部维护对事件处理程序的引用(可能使用enable_shared_from_this)?
谢谢
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 reference to event handler be maintained from within the event handler itself (probably using enable_shared_from_this)?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在成员变量中保存指向自身的共享指针将违背shared_ptr的目的,因为您需要以某种方式通知对象不再需要它(这就是“删除obj”的目的,我们试图避免使用智能指针) .
作为解决方案之一:如果可能的话,用shared_ptr(或weak_ptr)替换第三类中的原始指针。
其他解决方案在很大程度上取决于应用程序的设计,例如,您可以以某种方式强制命令从管理器中删除指针...
尝试研究此文档 http://www.boost.org/ doc/libs/1_43_0/libs/smart_ptr/sp_techniques.html,也许你会发现一些对你有用的东西。
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.