
Hello All, I have a couple of classes that I want to self register themselves with a monitoring class. To do this they must pass a shared_ptr of themselves to the monitor register function. Therefore I need to make a shared_ptr form the this pointer, in the constructor. I have derived my classes from enabled_shared_from_this...(code to get monitor omitted) //psuedo code.. monitor::AddSource1(boost::shared_ptr<CSource1>); monitor::AddSource2(boost::shared_ptr<CSource2>); class CSource1 : public enable_shared_from_this<CSource1> { CSource1() { Monitor->AddSource(shared_from_this()); }; } and class CSource2 : public base1, public enable_shared_from_this<CSource2> { CSource2() { Monitor->AddSource(shared_from_this()); };} } This all compile fine, but when run, the shared_from_this call asserts with a bad weak ptr - at the time of calling the weak_ptr has no content, and looking at the boost code, I cannot see where it is supposed to get set to access the this value. Should I be using enable_shared_from_this in this way or is there a better way to convert the this ptr to a shared_ptr in a constructor that I need to use. James

On 3/20/06, James Hughes
Hello All,
I have a couple of classes that I want to self register themselves with a monitoring class. To do this they must pass a shared_ptr of themselves to the monitor register function.
Therefore I need to make a shared_ptr form the this pointer, in the constructor.
I have derived my classes from enabled_shared_from_this...(code to get monitor omitted)
//psuedo code.. monitor::AddSource1(boost::shared_ptr<CSource1>); monitor::AddSource2(boost::shared_ptr<CSource2>);
class CSource1 : public enable_shared_from_this<CSource1> { CSource1() { Monitor->AddSource(shared_from_this()); }; }
and
class CSource2 : public base1, public enable_shared_from_this<CSource2> { CSource2() { Monitor->AddSource(shared_from_this()); };} }
This all compile fine, but when run, the shared_from_this call asserts with a bad weak ptr - at the time of calling the weak_ptr has no content, and looking at the boost code, I cannot see where it is supposed to get set to access the this value.
Should I be using enable_shared_from_this in this way or is there a better way to convert the this ptr to a shared_ptr in a constructor that I need to use.
James
I suspect you're running foul of this condition on enable_shared_from_this: "There must exist at least one shared_ptr instance p that owns t." If you're using something like: boost::shared_ptr<CSource1> pSource(new CSource1); then when the CSource1 constructor is executed, the raw pointer hasn't been assigned to the shared pointer yet. HTH Stuart Dootson
participants (2)
-
James Hughes
-
Stuart Dootson