Boost logo

Boost Users :

Subject: Re: [Boost-users] [shared_ptr] Multiple enable_shared_from_this in inheritance tree
From: ivan.lelann_at_[hidden]
Date: 2012-03-28 05:08:21


----- Mail original -----
> De: "Edward Diener" <eldiener_at_[hidden]>
> À: boost-users_at_[hidden]
> Envoyé: Mercredi 28 Mars 2012 01:56:24
> Objet: Re: [Boost-users] [shared_ptr] Multiple enable_shared_from_this in inheritance tree
>
> On 3/27/2012 5:08 AM, ivan.lelann_at_[hidden] wrote:
> >
> >snip...
> >> My main point is that if having more than one
> >> enable_shared_from_this<>
> >> in the inheritance hierarchy normally fails, this should be
> >> documented
> >> with the proper information on how to workaround the problem.
> >>
> >
> > I agree.
> >
> > I wondered how current C++11 standard libraries handled this.
> > With VS2010, replacing "boost" with "std" made both
> > "shared_from_this()" calls throw.
> > (with two esft bases the compiler chooses a dummy specialization)
>
> I think it is quite simply that there can not be more than one
> enable_shared_from_this derivation in a hierarchy. Unfortunately one
> is
> left to discover this for himself.

IIRC, with g++ (4.6) using its C++11's std instead of boost, I got a compile-time error.
Something like "... is ambiguous". I'll try to check that as it is quite self-documenting.

I failed to see how one can properly implement enable_shared_from_this without extra compiler support.
BTW, you can throw even without multiple esft. With boost or VS2010's std:

struct A { virtual void foo() {};};

struct B : A, boost::enable_shared_from_this <B> {};

int main()
{
        A * pa = new B;

        boost::shared_ptr <A> spa (pa); // dummy sp_enable_shared_from_this called here as A do not inherit esft
                                        // shared_ptr <A> spa (new B) would have been ok

        boost::dynamic_pointer_cast <B> (spa)->shared_from_this(); // shared_from_this() throws bad_weak_ptr

        return 0;
}

Regards,
Ivan


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