On Mon, Jun 24, 2013 at 11:22 AM, Adam Romanek
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.htmlhttp://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.
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.
Agreed.