开发者

Reference counted smart pointer that deletes owned object with ref count greater than zero?

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 lik开发者_开发技巧e 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


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.

  • Use wrapper objects as the members of the queues. A logically queued object has two wrapper objects, one for each queue.
  • Each wrapper contains a boost::shared_ptr to the object logically a member of each queue.
  • The wrapper's destructor marks the logically queued object as dead.
  • When pulling items off the queue, ignore the ones marked dead.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜