2

Just read What is the usefulness of `enable_shared_from_this`?, still don't understand why it's useful.

Like said in the 2nd top answer:

When you do this, keep in mind that the object you call shared_from_this on must be owned by a shared_ptr object. ...

My question: since we already have a shared_ptr object, why still need shared_from_this instead of a simple copy or assignment?


Update: thanks to Kerrek SB and Igor Tandetnik, I think I understand now, also, in Weak Pointers referenced in What is the usefulness of `enable_shared_from_this`? there is already a example:

Sometimes member functions return a pointer or reference to the object that they were applied to, to support chaining of operations.

Gang YIN
  • 2,509
  • 2
  • 21
  • 25
  • 3
    It allows you to manufacture a `shared_ptr` from inside the object's method - where you have `this`, but don't have the `shared_ptr` that the caller is holding. – Igor Tandetnik Jul 05 '15 at 00:26
  • 4
    We **don't** "already have a shared_ptr object"! That's the whole point. We have an object that we know is owned by *some* shared pointer somewhere that we can't see. – Kerrek SB Jul 05 '15 at 00:31
  • Adding to @KerrekSB: Producing a new `shared_ptr(this)` instead of `enable_shared_from_this` would result in double destruction of the object because two different reference counts keep track of the object – WorldSEnder Jul 05 '15 at 01:13
  • @IgorTandetnik, so one of object's method could manufacture a shared_ptr, then it will return the shared_ptr to the caller? could you share a real world example for this? – Gang YIN Jul 05 '15 at 01:20
  • @KerrekSB, i think i understand for the double destruction part to be avoided, but not for the "we know is owned by some shared pointer somewhere that we can't see", could you please share some example for this? – Gang YIN Jul 05 '15 at 01:22
  • 2
    @GangYin: Suppose a class has only private constructors and a public, static factory function returning a shared pointer. Then each class member function can assume that `*this` is owned by a shared pointer. – Kerrek SB Jul 05 '15 at 01:25
  • 1
    @KerrekSB, so the outside world could get a shared pointer through the factory function, then why still need another member function for outside to get a shared pointer? instead of just make a copy of that already got shared pointer? – Gang YIN Jul 05 '15 at 01:31
  • 1
    @GangYin: For member functions! – Kerrek SB Jul 05 '15 at 02:08
  • 2
    `then it will return the shared_ptr to the caller?` Not necessarily - that would indeed be somewhat silly. But it could pass this `shared_ptr` along to another object; e.g. register itself with a cache manager of some kind. – Igor Tandetnik Jul 05 '15 at 02:55

0 Answers0