B. D
B. D

Reputation: 7798

How useful is std::enable_shared_from_this if you already have a std::shared_ptr at your disposal?

I have stumbled on std::enable_shared_from_this, notably on this similar question, but I still don't understand what is the point

The recurring example is the following :

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();
}

But I don't get this example, if I were in this situation I would just do :

int main()
{
    shared_ptr<Y> p(new Y);
    shared_ptr<Y> q = p; // Results in exactly the same thing
}

Thanks

Edit : I think the person who closed the question did not understand my intent. The post is marked as duplicate of another post, while the very first line of this post links to that very same "other post". I have a question which the so-called duplicate has no answer for.

To be specific, a class implementing enable_shared_from_this needs to be created as a std::shared_ptr. So you have access to that shared_ptr. My question was (in the title mind you), "Because you are forced to have a std::shared_ptr anyways, does keeping track of it actually renders std::enable_shared_from_this useless/redundant?"

Upvotes: 2

Views: 275

Answers (1)

paddy
paddy

Reputation: 63471

Two use cases immediately spring to mind:

  1. It allows the object to hand itself off to something else that then keeps a shared pointer. The object itself doesn't own a shared copy. The point of shared_from_this is to give the object an internal weak_ptr.

  2. Since passing shared pointers around is expensive (and redundant, when you know it's always owned within a call stack), it is standard practice to pass around the contained object as a reference. If, somewhere down the call stack, you need to obtain the shared pointer again, you can do so via shared_from_this.

Upvotes: 2

Related Questions