Boost logo

Boost :

From: Tom Titchener (Tom.Titchener_at_[hidden])
Date: 2006-09-20 11:48:09


I'd like to build a chain of objects with an upper layer holding a shared_ptr to a lower layer and the lower layer holding a weak_ptr back to the upper layer. The upper layer users the shared_ptr for control. The lower layer uses the weak_ptr for callbacks (first calling lock to convert it to a shared_ptr). And ... I'd like to do it in my class ctors. That's the kicker. It *seems* like the shared_from_this framework should give me what I want...

#include <boost/weak_ptr.hpp>

#include <boost/shared_ptr.hpp>

#include <boost/enable_shared_from_this.hpp>

class CIControl {

    virtual bool ControlOne(const bool) = 0;

};

typedef boost::shared_ptr<CIControl> CIControlSPtr;

class CICallback {

    virtual bool OnControlOneComplete(const bool) = 0;

};

typedef boost::weak_ptr<CICallback> CICallbackWPtr;

typedef boost::shared_ptr<CICallback> CICallbackSPtr;

class CSlave : public CIControl {

    const CICallbackWPtr pUp_;

public:

    CSlave(const CICallbackSPtr& p) : pUp_(p) { }

    bool ControlOne(const bool a) { return a; }

};

class CMaster : public CICallback, public CIControl, public boost::enable_shared_from_this<CMaster> {

    CIControlSPtr pDown_;

public:

    CMaster() : pDown_(CIControlSPtr(new CSlave(shared_from_this())) {}

    bool ControlOne(const bool a) { return a; };

    bool OnControlOneComplete(const bool a) { return a; }

};

void main(void) {

    CIControlSPtr p(new CMaster());

}

Heck, it compiles and links Ok... :) But when I run it, shared_from_this() in the CMaster() ctor initializer for pDown_ asserts. It looks to me like the problem is there's no shared_ptr for CMaster itself, yet. We're still in the ctor, we have yet to return to main() to initialize "CIControlSPtr p".

One answer is two-part initialization. First the ctor. Then a "bind" method to pass the fully-constructed shared_ptr down to the lower class to so it can initialize it's weak pointer back up. But it'd be nicer to do it in the ctor. For one thing, the weak_ptr can be const.

I remember solving a similar problem creating COM objects wrapped in smart pointers by artificially bumping the refcount up (and down again) during object creation. But I haven't got my boost-brains sufficiently revved up to figure out if such a trick is possible in boost.

Thanks,

Tom Titchener


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk