Subject: Re: [boost] [smart_ptr] enable_shared_from_this and shared_ptr to a base class
From: Andrey Semashev (andrey.semashev_at_[hidden])
Date: 2013-06-24 03:38:19
On Mon, Jun 24, 2013 at 11:22 AM, Adam Romanek <romanek.adam_at_[hidden]>wrote:
> On 06/24/2013 08:52 AM, Andrey Semashev wrote:
>> On Mon, Jun 24, 2013 at 10:28 AM, Adam Romanek <romanek.adam_at_[hidden]
>>> 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);
>> This is expected, given the way it's implemented and described.
>> shared_from_this() description  mentions that there must be at least
>> shared_ptr that owns the object. I didn't find any formal definition of
>> "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.
> 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.
The shared_ptr has no knowledge of Y since it is not constructed with a
pointer to Y. Actually, without a virtual destructor (like in your code) Y
is never destructed. So from the pointer's standpoint, it doesn't own Y,
but it owns X.
I know, this may not be obvious and it deserves better documentation.
> 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.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk