Boost logo

Boost Users :

Subject: Re: [Boost-users] shared_from_this - derived classes (yes, I googled)
From: Igor R (boost.lists_at_[hidden])
Date: 2011-10-02 03:29:12


> Well, I tried to get a trivial example and ended up having a working example. I
> suppose my problem is in the non-trivial part of my code :)
>
> Is this the correct way to do it?
>
>
> #include <iostream>
>
> #include <boost/enable_shared_from_this.hpp>
> #include <boost/shared_ptr.hpp>
>
> //--------------------------
> class A : public boost::enable_shared_from_this<A>
> {
> public:
>
>    ///
>    typedef boost::shared_ptr<A> SmartPtr;
>
>    ///
>    static A::SmartPtr Create()
>    {
>        A::SmartPtr instance;
>
>        // Check arguments if any
>
>        // Create an instance of this class
>        instance.reset(new A());
>
>        return instance;
>    }
>
>    virtual ~A()
>    {
>    }
>
> protected:
>
>    A()
>    {
>    }
>
> };
>
> //--------------------------
> class B : public A
> {
> public:
>
>    ///
>    typedef boost::shared_ptr<B> SmartPtr;
>
>    ///
>    static B::SmartPtr Create()
>    {
>        B::SmartPtr instance;
>
>        // Check arguments if any
>
>        // Create an instance of this class
>        instance.reset(new B());
>
>        return instance;
>    }
>
>    ///
>    virtual ~B()
>    {
>    }
>
>    ///
>    B::SmartPtr Foo()
>    {
>        A::SmartPtr temp = shared_from_this();
>        B::SmartPtr me   = boost::shared_dynamic_cast<B, A>(temp);
>
>        return me;
>    }
>
>    ///
>    void Bar() const
>    {
>        std::cout << "Success!" << std::endl;
>    }
>
> protected:
>
>    ///
>    B()
>        :
>        A()
>    {
>    }
> };
>
> //--------------------------
> int main()
> {
>    B::SmartPtr b1 = B::Create();
>    B::SmartPtr b2 = b1->Foo();
>
>    if( b1 != b2 )
>    {
>        std::cout << "they aren't equal." << std::endl;
>        return 1;
>    }
>
>    b2->Bar();
>
>
>    return 0;
> }

Your example compiles and works well.
(Actually, you don't need shared_dynamic_cast here,
static_pointer_cast would be well enough.)


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