Getting a shared_ptr referring to this

suggest change

std::enable_shared_from_this allows an object already managed by a std::shared_ptr to obtain another shared_ptr that shares the same ownership.

Deriving publicly from std::enable_shared_from_this<T> provides a shared_from_this() member function.

The object must already be owned by a shared_ptr. Prefer std::make_shared:

#include <memory>

class A : public std::enable_shared_from_this<A> {
};

int main() {
    auto first = std::make_shared<A>();
    std::shared_ptr<A> second = first->shared_from_this();
    // first and second share ownership; first.use_count() is 2 here.
}

Do not call shared_from_this() in the constructor: the owning shared_ptr has not yet initialized the object's weak ownership link.

#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();
    ...
}

Since C++17, calling shared_from_this() when no shared_ptr owns the object throws std::bad_weak_ptr. Code written for earlier standards should not rely on a defined outcome.

During construction, the object is not yet linked to the shared_ptr control block, even when it is being created by std::make_shared.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents