引用计数智能指针删除引用计数大于零的拥有对象?
我有一个设计,其中对象同时由 2 个队列拥有。有时队列本身可能会被删除。在这种情况下,队列中的所有对象都必须被删除并从它们所在的另一个队列中删除。
当前的解决方案让拥有的对象知道两个拥有的队列,但这引入了丑陋的耦合。
有智能指针类可以帮助我吗?构造可以使用“新”指针或现有指针的副本。销毁将删除所拥有的资源。 Access 就像一个weak_ptr,提供了指向null 的可能性。
我想它可能需要一个特定的“销毁”方法,以确保指针的临时副本不会释放资源。
有谁知道这样的事情吗?
谢谢, 托尼
I have a design where objects are simultaneously owned by 2 queues. Occasionally the queues themselves may be deleted. In this case, all objects in the queue must be deleted and removed from the other queue they are in.
The current solution has the owned objects knowing about the two owning queues, but this introduces ugly coupling.
Is there a smart pointer class that could help me? Construction would be either with a 'new' or a copy of an existing pointer. Destruction would delete the owned resource. Access would be like a weak_ptr, giving the possibility of pointing to null.
I guess it might need a specific 'destroy' method, to make sure that temporary copies of pointers didn't free the resource.
Does anyone know of anything like this?
Thanks,
Tony
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您希望删除排队对象以将其从另一个队列中删除,而不将其耦合到队列。
避免这种耦合的一种方法是将对象标记为已删除,而不实际删除它。
You want deletion of a queued object to remove it from the other queue, without coupling it to the queue.
One approach that would avoid this coupling would be to mark the object as removed, without actually removing it.
一般来说,在存在引用循环的情况下,没有任何可重用的引用计数解决方案。有一些解决方案,但它们要么特定于允许的引用循环模式,要么特定于垃圾收集器。根据您描述问题的方式,您需要能够弄清楚给定队列拥有哪些对象(以便您可以删除该队列)以及哪些队列拥有给定对象(以便您可以从所有队列中删除对象)。所以你有参考周期。
为了解决丑陋的耦合问题,我建议让队列包含代理对象,每个代理对象都拥有真实的对象并知道哪些队列拥有它。队列方法将使用并更新这些代理对象。
Generally speaking, there aren't any reusable solutions to reference counting in the presence of reference cycles. There are solutions, but they are either specific to the pattern of reference cycles that's allowed, or garbage collectors. From the way you described the problem, you need to be able to figure out both what objects a given queue owns (so you can delete the queue) and what queues own a given object (so you can remove an object from all queues). So you have reference cycles.
To fix the ugly coupling problem, I would suggest having queues contain proxy objects, each of which owns the real object and knows what queues own it. The queue methods would use and update these proxy objects.