I ran across enable_shared_from_this while reading the Boost.Asio examples and after reading the documentation I am still lost for how this should correctly be used. Can someone please give me an example and/or and explanation of when using this class makes sense.
+27
A:
It enables you to get a valid shared_ptr
instance to this
, when all you have is this
. Without it, you would have no way of getting a shared_ptr to
this
, unless you had already one as a member. This example from the boost documentation for enable_shared_from_this:
class Y: public enable_shared_from_this<Y>
{
public:
shared_ptr<Y> f()
{
return shared_from_this();
}
}
int main()
{
shared_ptr<Y> p(new Y);
shared_ptr<Y> q = p->f();
assert(p == q);
assert(!(p < q || q < p)); // p and q must share ownership
}
The method f() returns a valid shared_ptr
, even though it had no member instance. Note that you cannot simply do this:
class Y: public enable_shared_from_this<Y>
{
public:
shared_ptr<Y> f()
{
return shared_ptr<Y>(this);
}
}
The shared pointer that this returned will have a different reference count from the "proper" one, and one of them will end up losing and holding a dangling reference when the object is deleted.
enable_shared_from_this
is going to be a part of the new C++0x standard as well, so you can also get it from there as well as from boost.
1800 INFORMATION
2009-04-03 02:00:52
+1. The key point is that the "obvious" technique of just returning shared_ptr<Y>(this) is broken, because this winds up creating multiple distinct shared_ptr objects with separate reference counts. For this reason you must never create more than one shared_ptr **from the same raw pointer**.
j_random_hacker
2009-04-03 02:31:42
Nice explanation of a concept that's difficult to get at first glance (at least it was for me).
Michael Burr
2009-04-03 04:43:26
Thank you very much, that clears things up a lot
MGoDave
2009-04-03 14:24:52