I read about std::enable_shared_from_this
and I understand how it works, but I don't understand what problem it designed to solve?
For example from here: What is the usefulness of `enable_shared_from_this`?
class Y: public std::enable_shared_from_this<Y>
{
public:
std::shared_ptr<Y> f()
{
return shared_from_this();
}
};
std::shared_ptr<Y> p(new Y);
std::shared_ptr<Y> q = p->f();
yeah, great we can write q=p->f();
, but why not just
q = p;
?
In general case we have shared_ptr
, but for some reason it is not available somewhere
, so we have to restore it from this
, but if we pass raw pointer from shared_ptr
to somewhere
then we have problem, because of all shared_ptr
safety go away if we take pointer from std::shared_ptr::get
,
and pass raw pointer to someone.