Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Memory and Utilities

C++ std::enable_shared_from_this

Reference for std::enable_shared_from_this: get a shared_ptr to the current object safely with shared_from_this(), weak_from_this() and bad_weak_ptr pitfalls.

std::enable_shared_from_this<T> is a base class template from <memory>. A class that derives from it can hand out shared_ptrs to itself with shared_from_this(), and those pointers share the same control block as the shared_ptr that already owns the object.

You need this when an object must pass itself to a callback, a queue or another owner while it is managed by a shared_ptr. Writing std::shared_ptr<T>(this) instead creates a second, unrelated control block, and the object is deleted twice.

C++
struct Session : std::enable_shared_from_this<Session> {
    std::shared_ptr<Session> self() { return shared_from_this(); }
};

Try it

C++ Handing out shared_ptr to this

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ Calling shared_from_this too early

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Syntax

C++
template<class T> class enable_shared_from_this {
public:
    shared_ptr<T>       shared_from_this();
    shared_ptr<const T> shared_from_this() const;
    weak_ptr<T>         weak_from_this() noexcept;        // C++17
    weak_ptr<const T>   weak_from_this() const noexcept;  // C++17
};
Member Description
shared_from_this() Returns a shared_ptr that shares ownership with the existing one.
weak_from_this() Returns a weak_ptr to the object; an empty one if no shared_ptr owns it yet.

Returns: smart pointers to *this. Errors: shared_from_this() throws std::bad_weak_ptr (since C++17) when the object is not currently owned by any shared_ptr. Before C++17 the behavior was undefined.

Usage notes

  • Derive publicly (struct T : std::enable_shared_from_this<T>), with T being the derived class itself (the curiously recurring template pattern). Private inheritance silently disables the mechanism.
  • shared_from_this() works only after a shared_ptr has taken ownership. Calling it in a constructor always fails, because the owning shared_ptr does not exist yet. Use a factory function that creates the object, then calls an init() method.
  • Do not call it from a destructor either: the object is already being destroyed.
  • Objects on the stack or created with a plain new that nobody wraps cannot use it.
  • A common pattern for asynchronous work is to capture shared_from_this() in a lambda so the object lives until the callback ends. Take care that this does not form a cycle (the object storing the lambda that owns the object). Capturing weak_from_this() and calling lock() inside the callback avoids that.
  • Hide the constructor and expose static std::shared_ptr<T> create(...) to make sure objects are always shared-owned.
  • It adds one weak_ptr worth of data to every object.