|
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