Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2002-06-25 13:41:18

From: "Phil Nash" <phil.nash.lists_at_[hidden]>
> Nothing major, just that, as counted_base seems to have been promoted out
> detail it seems odd to have to include detail/shared_count.hpp to get to

The documented way to get to counted_base would probably be shared_ptr.hpp.

> > No, you need to construct the counted_base with initial counts of zero
> > (there is a default constructor present.)
> Ok... this was how I tried it initially but I had other problems - in
> particular in the taking weak_ptrs in the constructor of the object being
> ref-counted... maybe that is not possible after all - you didn't answer
> bit before.

Yes, I see the problem. In the current implementation, you have to create an
owning pointer to the object first, before any weak pointers, since
counted_base interprets use_count = 0, weak_count != 0 as an indication that
dispose() has already been called.

So it seems that you can't create weak_ptr's in the object constructor. You
need a shared_ptr first, and you can't create a temporary shared_ptr to
'this' in the constructor since it will call dispose() on block exit.

> > Sorry, you can't do that. The counted_base must stay alive if there are
> > pointers to it, shared or weak; you must not 'delete this' in dispose().
> You
> > should release any resources that are managed by your object, but keep
> > alive. If you kill the counted_base, the weak pointers will try to
> decrement
> > a non-existent weak count, and crash.
> Ok, I see what you are saying, but doesn't that defeat the point of
> weak_ptr's in the case of intrusive counts?

weak_ptr's are somewhat an oddity in the intrusive case, but they still
work, in the sense that you can break cyclic dependencies with a weak_ptr. A
cyclic dependency means that your object has shared_ptr members that
(indirectly) lead back to that same object. You need to reset() these
shared_ptr members in dispose() to break the cycle.

> I can seem why it needs to be
> that way now you have pointed out to me what should have been obvious
> (doh!), but I'm sure I'm still missing something here. Is what I have just
> said true - that you can't use weak_ptrs with objects derived from
> counted_base (well, you can, but the weak_ptr's are no longer weak)?

They are semi-weak. :-)

> If so is there a way round this - such as detaching the weak_count into a
> seperate object from use_count?

Tough question.

Boost list run by bdawes at, gregod at, cpdaniel at, john at