I have been trying to understand the usefulness of inheriting from enable_shared_from_this although the working of this mechanism was somewhat explained there. I couldn't find the answer to this question on that post so I am posting it here.
In one of the examples there. The following example was given as a bad practice. I understand the reason for that which is the two shared pointers dont know of each other and once one of the shared pointer goes out of scope the resource will be destroyed.
struct S
{
shared_ptr<S> dangerous()
{
return shared_ptr<S>(this); // don't do this!
}
};
int main()
{
shared_ptr<S> sp1(new S);
shared_ptr<S> sp2 = sp1->dangerous();
return 0;
}
My question is why did the user not do this
shared_ptr<S> sp2 = sp1;
Wouldn't that just increase the reference count as well ? and be fine ? Is that example given incase for some reason the class does not have access to sp1 and needs to return back a shared_ptr ?