Boost logo

Boost :

From: abierbaum (allenb_at_[hidden])
Date: 2001-12-10 19:16:13


I have run across a problem in some code that I am trying to convert
to using shared_ptrs.

Basically it looks something like...

class A
{
public:
   init()
   {
      // Pass a ptr to myself to B so it can call me
      b_obj = new B(shared_ptr<A>(this));
   }

   B* b_obj;
}

class B
{
public:
   B(shared_ptr<A> aPtr)
   {
      a_obj = aPtr;
   }

   shared_ptr<A> a_obj;
}

Now in main...

int main()
{
   shared_ptr<A> a = new A;
   a->init();

   // Problem a and B::a_obj are
   // different shared_ptrs, pointing
   // to same object
}

The problem is that I only have one copy of object a in memory, but
there are two seperate shared_ptr impls pointing at it. So which ever
one goes to zero first is going to leave the other one with a dangling
pointer. Exactly what I was trying to prevent.

The problem boils down to:

How do I pass a reference to myself ( shared_ptr<TYPE>(this) ) to
someone else in a safe way?

Has anyone had to deal with this before? (I searched the list and
didn't come up with anything being discussed in the past)

More info: This problem is occuring in several places in a
multi-threaded networking module I am working on that uses a reactor
pattern to deal with network I/O. Basically the network streams need
to be initialized with ptrs to the objects that need to stream data to
(the routers and handlers). But these objects already have others
pointing at them. (sorry for the brief description :)

Thanks,
Allen


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