views:

25

answers:

1

I'm trying to use boost::shared_ptr and boost::enable_shared_from_this to no avail. It looks as if shared_from_this() is returning the wrong shared_ptr. Here is what I see:

Task* task = new TaskSubClass();
boost::shared_ptr<Task> first = boost::shared_ptr<Task>(task); // use_count = 1, weak_count = 1
boost::shared_ptr<Task> second = first; // use_count = 2, weak_count = 1
boost::shared_ptr<Task> third = first->shared_from_this(); // use_count = 2, weak_count = 2

I also noticed that first.px=third.px but first.pn.pi!=third.pn.pi. That is, they both share the same object but they use a different counter. How can I get the two to share the same counter?

+1  A: 

Turns out that this was caused by the fact that TaskSubClass's constructor invoked some method that, in turn, invoked new boost::shared_ptr<Task>(this) instead of new boost::shared_ptr<Task>(shared_from_this()). As an added bonus, you're not supposed to invoke shared_from_this() from the constructor and the documentation is far from obvious on this point: There must exist at least one shared_ptr instance p that owns t. It makes sense in retrospect, but the documentation should really be more explicit :)

Sorry for the misleading question.

Gili