On 06/24/2013 08:52 AM, Andrey Semashev wrote:
On Mon, Jun 24, 2013 at 10:28 AM, Adam Romanek
wrote: class X { ... };
class Y: public X, public boost::enable_shared_from_**this<Y> { ... };
int main() { X* x_ptr = new Y; boost::shared_ptr<X> sp(x_ptr); sp->foo(); }
This is expected, given the way it's implemented and described. shared_from_this() description [1] mentions that there must be at least one shared_ptr that owns the object. I didn't find any formal definition of the "owns" relation but it doesn't look to me that it applies to your example, because there is no shared_ptr pointing to Y in your code.
[1] http://www.boost.org/doc/libs/release/libs/smart_ptr/enable_shared_from_this...
Andrey! Thanks for such a quick response. OK, this behavior may in fact be expected considering the implementation. However, I would not say the documentation reflects that. But let's look at the code first. You wrote that there is no shared_ptr pointing to Y in my code. I can't agree. There is - sp. It points to Y through a pointer to X, which is perfectly valid. Moreover, in my opinion it "owns" an instance of Y and will attempt to destroy it when necessary. Maybe it's a matter of using the right words but a colleague of mine spent an hour or two looking for a bug in his code, just to find out about this "feature" of enable_shared_from_this. I appreciate your explanation but still, I think that the documentation is a bit imprecise and could be improved so that things were more clear. WBR, Adam Romanek