Search code examples
c++c++11shared-ptr

Cast 'this' to std::shared_ptr


I have a method on a class to make a particular instance an "active" instance:

void makeActive() { activeInstance = this; }

However it doesn't work since activeInstance has type std::shared_ptr< ClassName >. How can I cast this to std::shared_ptr<ClassName>?


Solution

  • If your object is already owned by a shared_ptr, you can produce another shared_ptr by having your object inherit from std::enable_shared_from_this

    This code will then work:

    void makeActive() { activeInstance = shared_from_this(); }
    

    If your object is not already owned by a shared_ptr, then you sure as heck don't want to create one in makeActive() since a shared_ptr will try to delete your object when the last one is destroyed.