C++ Smart Pointers Getting a shared_ptr referring to this


Example

enable_shared_from_this enables you to get a valid shared_ptr instance to this.

By deriving your class from the class template enable_shared_from_this, you inherit a method shared_from_this that returns a shared_ptr instance to this.

Note that the object must be created as a shared_ptr in first place:

#include <memory>
class A: public enable_shared_from_this<A> {
};
A* ap1 =new A();
shared_ptr<A> ap2(ap1); // First prepare a shared pointer to the object and hold it!
// Then get a shared pointer to the object from the object itself
shared_ptr<A> ap3 = ap1->shared_from_this(); 
int c3 =ap3.use_count(); // =2: pointing to the same object

Note(2) you cannot call enable_shared_from_this inside the constructor.

#include <memory> // enable_shared_from_this

class Widget : public std::enable_shared_from_this< Widget >
{
public:
    void DoSomething()
    {
        std::shared_ptr< Widget > self = shared_from_this();
        someEvent -> Register( self );
    }
private:
    ...
};

int main()
{
    ...
    auto w = std::make_shared< Widget >();
    w -> DoSomething();
    ...
}

If you use shared_from_this() on an object not owned by a shared_ptr, such as a local automatic object or a global object, then the behavior is undefined. Since C++17 it throws std::bad_alloc instead.

Using shared_from_this() from a constructor is equivalent to using it on an object not owned by a shared_ptr, because the objects is possessed by the shared_ptr after the constructor returns.