Boost logo

Boost :

From: Greg Colvin (gcolvin_at_[hidden])
Date: 1999-08-01 00:30:12


Although it seems impossible to create a non-intrusive weak
pointer class that can track the liveness of an arbitrary class of
object, it is possible to create one that tracks the liveness of
objects controlled by shared_ptr.

The changes to out current shared_ptr would be:

   Switch to the "indirect" implementation of shared_ptr. That
   is, the shared_ptr contains just a pointer to a handle struct
   containing a pointer to the object shared and the count.

   Add a second count field for the number of weak pointers using
   the object. When the number of shared pointers goes to zero
   the shared object is deleted and the pointer to object field is
   zeroed out, but the handle struct is not deleted until both
   counters go to zero.

So the code could be, in part:

   template<typename T> struct shared_hdl {
      T* p;
      long n_shared, n_weak;
   };

   template<typename T> class shared_ptr {
      // ...
      void dispose() {
         if (--*ph->n_shared == 0) {
            delete ph->p;
            if (ph->n_weak == 0)
               delete ph;
            else
               ph->p = 0;
         }
      }
      shared_hdl<T>* ph;
   };

   template<typename T> class weak_ptr {
      // ...
      void dispose() {
         if (--*ph->n_weak == 0 && ph->n_shared == 0)
            delete ph;
      }
      shared_hdl<T>* ph;
    };

The net costs are whatever the indirection costs (nothing much,
according to my measurements, it might even be a net gain) plus
the space for the extra counter, which is amortized over all the
weak pointers using it. Also, I suspect having two counters will
complicate adding thread safety.

------------------------------------------------------------------
Greg Colvin greg_at_[hidden] gcolvin_at_[hidden]


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