Boost logo

Boost :

From: David B. Held (dheld_at_[hidden])
Date: 2003-01-30 16:50:25


"Peter Dimov" <pdimov_at_[hidden]> wrote in message
news:005901c2c8a3$e5f86180$1d00a8c0_at_pdimov2...
> From: "David B. Held" <dheld_at_[hidden]>
> > ~ref_counted()
> > {
> > delete pCount_;
> > }
> >
> > bool release(P const&)
> > {
> > if (!--*pCount_) return true;
> > pCount_ = 0;
> > return false;
> > }
>
> Doesn't release() leak pCount_? Who is responsible for destroying
> the count?

The last guy out the door shuts off the lights. This isn't any different
from shared_ptr. If you make a copy, count goes from 1 to 2. When
the second guy dies, he calls release(), which drops the count to 1.
Since someone else is still using the count, we null our pointer, so
that we don't delete it. When the last guy dies, he calls release, which
drops the count to 0, and returns true, signalling "relinquish the
resource, it is no longer being shared". Then, the d'tor will delete
the count. Here it is in pseudocode:

smart_ptr<int> p1(new int(42)); // count = new int(1)
smart_ptr<int> p2(p1); // ++*count == 2
~p2();
    p2->release(); // --*count == 1, count = 0
    p2->~ref_counted(); // delete 0;
~p1();
    p1->release(); // --*count == 0
    p1->~ref_counted(); // delete count;

Is that clearer?

Dave


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk