Boost logo

Boost Users :

From: Yaoltzin Gomez (yaoltzin_at_[hidden])
Date: 2007-05-26 03:13:13


Hello everyone

Here's my problem. I have a small set of classes (I'm working on an API).
Some of the classes use inheritance hierarchy. Sometimes I need to use (well
lots of times) the "this" pointer and work with raw pointers inside each
class. However, I would like to work with smart pointers. So I need to
change the signature of my member functions to accept smart pointers, but
now I need an "this" smart pointer equivalent. I derived the classes from
boost::enable_shared_from_this.

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();
    }

    void Bar()
    {
       AnotherFunction( GetDerivedPointer() );
       ...
    }
};

Now, in the main function I have:

int main(...)
{
    boost::shared_ptr<Derived> derived( new Derived );

    derived->Foo();
    derived->Bar();
}

Obviously, this causes a bad_weak_ptr exception, because I'm creating a
Derived instance, and the shared_from_this called inside Foo throws the
exception, but I need to call this functions defined in the Base class.

In other words, I need access to the shared_from_this, in Base and Derived,
and right now I can't do this. I would like to know if it's possible to use
shared_from_this in this way, or not, and if not, what other options do I
have (besides using raw pointers)

This is a simplified problem, in my code, generally I have more than 2 leves
of class inheritance, so things get more complicated.

I hope I explained myself correctly. Thanks in advance.



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