Boost.enable_shared_from_this and create another shared_ptr <T>
I recently ran into an issue with an improved smart pointer. To be specified, enable_shared_from_this keeps "this" shared_ptr for class T. When an instance of T goes out of scope, enable_shared_from_this still remains. But how do I create a new shared_ptr object of the original ptr? What's the difference?
Many thanks.
class Foo : public boost::enable_shared_from_this<Foo>
{};
int main() {
shared_ptr<Foo> p1(new Foo);
shared_ptr<Foo> p2 = p1->shared_from_this();
shared_ptr<Foo> p3 = shared_ptr<Foo>(p1);
p1.reset();
// p1 is released, p2 and p3 still remains.
// but what is the diff between p2 and p3?
// Can I say shared_from_this() works the same way as
// shared_ptr<Foo>(p1);
}
source to share
This will likely crash your program when your new pointer goes out of scope. The reason for this is that shared_ptr manages the lifetime of your object by counting references to it. Every time you copy a shared_ptr it increases the reference count, every time a shared_ptr object goes out of scope it decreases the reference count. When the reference count reaches zero, it will delete the object. When the shared_ptr
one created inside a class method goes out of scope, it will remove that because the reference count will be zero.
So, shared_from_this
should be used when you need shared_ptr
inside a class member function, whereas in any other case you can just use a generic object pointer.
Consider the following example:
class Y
{
public:
shared_ptr<Y> f()
{
return shared_ptr<Y>(this);
}
}
If you returned a normal shared pointer here, you must create multiple shared_ptrs
for the same pointer, which will then delete at some point this
, leaving all other instances shared_ptr
dangling (pointing to something that was deleted). So the correct version is:
class Y: public enable_shared_from_this<Y>
{
public:
shared_ptr<Y> f()
{
return shared_from_this();
}
}
source to share