2

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?"

Community
  • 1
  • 1
B. Decoster
  • 7,723
  • 1
  • 32
  • 52
  • That's all well and good when you have `p`. What if you're inside of `Y` and need to pass a `shared_ptr` to `this` to something? – Barry Sep 16 '16 at 01:25

1 Answers1

2

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.

paddy
  • 60,864
  • 6
  • 61
  • 103
  • 1
    Good answer and UV'ed, I think it's worth mentioning that in *most* cases it's better to avoid these tools. For instance, calling a function by reference from your smart pointer'ed object generally guarantees that it will not have its ownership semantics messed with, `shared_from_this` basically throws that away. Of course, you may have a good reason to throw that away, but you should indeed require a good reason. – Nir Friedman Oct 12 '16 at 19:47