Boost logo

Boost Users :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2002-11-26 07:49:26


From: "Hickman, Greg" <greg.hickman_at_[hidden]>
> I need an object managed through a shared_ptr to be able to pass itself
> (i.e., this) to another object which also expects a shared_ptr. Is there
a
> preferred implementation technique for this when using the boost smart
> pointers?

Yes, there is now.

The possible solutions depend on the location where you want to extract a
shared_ptr to 'this'. If you need to do this in the constructor, use a
static factory function:

class X
{
private:

    X();

public:

    static shared_ptr<X> create()
    {
        shared_ptr<X> px(new X);
        // do something with px
        return px;
    }
};

If you need to obtain a shared_ptr to this in a nonvirtual member function
X::f, consider replacing it with a free function:

void f(shared_ptr<X> this_, ...);

If 'f' is virtual, have the object store a weak_ptr to itself:

class X
{
private:

    weak_ptr<X> weak_this;

    X();
    X(X const &);
    X& operator=(X const &);

public:

    static shared_ptr<X> create()
    {
        shared_ptr<X> px(new X);
        px->weak_this = px;
        return px;
    }

    shared_ptr<X> shared_from_this()
    {
        shared_ptr<X> px(weak_this);
        return px;
    }

    shared_ptr<X const> shared_from_this() const
    {
        shared_ptr<X const> px(weak_this);
        return px;
    }
};

The current CVS version of shared_ptr includes explicit support for this
idiom, a base class template enable_shared_from_this<> that supplies the
shared_from_this member function. It's even documented. ;-)

> I think I've seen conversation in the past about deriving from
> boost::counted_base and calling shared_from_this(), but I think I also
> remember seeing comments to the effect that this is going away.

Yes, you are right. This is going away.


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