I am looking into the boost documentation for shared_ptr and enable_shared_from_this and I can not figure out practical use of enable_shared_from_this.
Below is my understanding of enable_shared_from_this (example copied from What is the usefulness of `enable_shared_from_this`?).
class Y: public enable_shared_from_this<Y>
{
public:
Y(): count(3){}
shared_ptr<Y> f()
{
return shared_from_this();
}
int count;
}
int main()
{
shared_ptr<Y> p(new Y);
shared_ptr<Y> q = p->f();
cout << "\n Count from P is " << p1->count;
cout << "\n Count from q is " << q1->count;
}
So, now we have a shared pointer q which points to the same object owned by p (new Y) and the object gets destroyed when both p and q go out of scope. And both the print statements above will print 3 as the count.
Now, I can achieve the same thing without the use of enable_shared_from_this by doing below.
class Y
{
public:
Y(): count(3){}
int count;
}
int main()
{
shared_ptr<Y> p(new Y);
shared_ptr<Y> q(p);
cout << "\n Count from P is " << p1->count;
cout << "\n Count from q is " << q1->count;
}
Even in the above example both P and Q point to the same object and will print 3.
So, what benefit am I getting by using the enable_shared_from_this?