Boost logo

Boost Users :

From: James Hughes (JHughes_at_[hidden])
Date: 2006-03-20 05:57:02


> -----Original Message-----
> From: David Klein [mailto:d.klein_at_[hidden]]
> Sent: 20 March 2006 10:27
> To: boost-users_at_[hidden]
> Subject: Re: [Boost-users] enable_shared_from_this - or an
> alternative..
>
>
> boost-users-bounces_at_[hidden] wrote:
> > Hello All,
> >
> > I have a couple of classes that I want to self register themselves
> > with a monitoring class. To do this they must pass a shared_ptr of
> > themselves to the monitor register function.
> >
> > Therefore I need to make a shared_ptr form the this pointer, in the
> > constructor.
> >
> > I have derived my classes from
> enabled_shared_from_this...(code to get
> > monitor omitted)
> >
> > //psuedo code..
> > monitor::AddSource1(boost::shared_ptr<CSource1>);
> > monitor::AddSource2(boost::shared_ptr<CSource2>);
> >
> > class CSource1 : public enable_shared_from_this<CSource1>
> > {
> > CSource1() { Monitor->AddSource(shared_from_this()); };
> > }
> >
> > and
> >
> > class CSource2 : public base1, public
> > enable_shared_from_this<CSource2> {
> > CSource2() { Monitor->AddSource(shared_from_this()); };}
> > }
> >
> >
> > This all compile fine, but when run, the shared_from_this call
> > asserts with a bad weak ptr - at the time of calling the
> weak_ptr has
> > no content, and looking at the boost code, I cannot see where it is
> > supposed to get set to access the this value.
> >
> > Should I be using enable_shared_from_this in this way or is there a
> > better way to convert the this ptr to a shared_ptr in a constructor
> > that I need to use.
> >
> >
> > James
> > _______________________________________________
> > Boost-users mailing list
> > Boost-users_at_[hidden]
> > http://lists.boost.org/mailman/listinfo.cgi/boost-users
>
> hi james,
>
> see: http://boost.org/libs/smart_ptr/sp_techniques.html#in_constructor
>
> HTH dave
> _______________________________________________
> Boost-users mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users

Thanks Dave, that does cover the problem well.

However, I cannot use the null deleter mechanism suggested as the shared_ptr
is passed on to monitor and is used there. The second scheme, using a
factory fucntion, would seem to be approriate, however, how to I handle
creation when the CSource1 class is actually to be used as a base class? If
the factory function is in CSource1, it doesnt know about any derived
classes. I don't want to have to write factory functions in every dervied
class - that seems a waste. Is there a correct technique for getting around
this issue? I am assuming a template of some description, but now sure what
that entails.

James

>


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net