0

What is the point for a class T to inherit from std::enable_shared_from_this<T> ? I can't seem to figure out why you wouldn't just create a std::shared_ptr<this> ?

jojeyh
  • 276
  • 1
  • 3
  • 12
  • First of all, `this` isn't a type, you can't give it as a template argument to `shared_ptr`. Then the purpose is to allow safe creation of `shared_ptr` to `this` in the object. – Rerito Nov 14 '17 at 12:08

1 Answers1

1

Cppreference has a good example on why.

If you want to return a std::shared_ptr of this while *this is already owned by a std::shared_ptr and you don't return shared_from_this() but return a new std::shared_ptr<T>(this) instead then you will end up with 2 shared pointers that don't know they're both owning the same object and thus the use_count() will be wrong which will cause a double delete, which is undefined behavior.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122