Boost logo

Boost Users :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2007-05-26 11:36:10


Yaoltzin Gomez wrote:

> Basically, what I have is this:
>
> class Base : public boost::enable_shared_from_this<Base>
> {
> boost::shared_ptr<Base> GetBasePointer()
> {
> return shared_from_this();
> }
>
> void Foo()
> {
> shared_ptr<Child> child( new Child );
> AddChild( child, GetBasePointer() );
> }
> };
>
> class Derived: public Base, public
> boost::enable_shared_from_this<Derived> {
> boost::shared_ptr<Derived> GetDerivedPointer()
> {
> return shared_from_this();
> }

[...]

One way to avoid putting more than one enable_shared_from_this<> base into
Derived is to use

class Derived: public Base
{
    boost::shared_ptr<Derived> GetDerivedPointer()
    {
       return dynamic_pointer_cast<Derived>( shared_from_this() );
    }

    // ...
};

static_pointer_cast will also work in this case (it will fail if Derived
uses virtual inheritance).


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