In a C++ async server, why must a session use enable_shared_from_this instead of std::shared_ptr<Session>(this), and when does shared_from_this() throw?
answer
- a second control block
- the hidden weak_ptr member
- filled in by the first owner
- constructors and stack objects
- public and unambiguous base
basics
~20 sstd::shared_ptr<Session>(this) creates a second control block, so two owner groups each delete the session. enable_shared_from_this keeps a weak_ptr set by the first owning shared_ptr; shared_from_this() copies it and, since C++17, throws std::bad_weak_ptr if nothing owns the object.
solid answer
~50 sEach `shared_ptr` constructor that takes a raw pointer starts a **new** control block, so `std::shared_ptr<Session>(this)` inside a member function creates a second owner group beside the registry's: whichever group drops to zero first deletes the session, and the other deletes it again. Deriving `Session` from `std::enable_shared_from_this<Session>` adds a hidden `weak_ptr` that the first owning `shared_ptr` constructor — including `make_shared` — fills in. `shared_from_this()` then returns a `shared_ptr` that joins the existing group, which is what an async read captures to keep the session alive until its callback runs. Since C++17 it throws `std::bad_weak_ptr` when no `shared_ptr` owns the object: in the constructor, for a stack or `unique_ptr`-owned object, or when the base is private or ambiguous so the hidden pointer was never set. `weak_from_this()` returns that `weak_ptr` for callbacks that must not extend the lifetime.
code
cpp · 31 lines#include <cstdio>
#include <functional>
#include <memory>
#include <string>
#include <vector>
std::vector<std::function<void()>> pending_io; // stands in for an I/O event loop
class Session : public std::enable_shared_from_this<Session> {
public:
explicit Session(std::string user) : user_(std::move(user)) {}
~Session() { std::printf("~Session %s\n", user_.c_str()); }
void start_read() {
auto self = shared_from_this(); // the callback co-owns the session
pending_io.push_back([self] { std::printf("read for %s\n", self->user_.c_str()); });
}
private:
std::string user_;
};
int main() {
auto s = std::make_shared<Session>("ann");
s->start_read();
s.reset(); // registry dropped it; the callback still owns it
for (auto& cb : pending_io) cb();
pending_io.clear(); // last owner gone: ~Session runs here
Session on_stack("bob"); // not owned by any shared_ptr
try { on_stack.start_read(); }
catch (const std::bad_weak_ptr& e) { std::printf("caught: %s\n", e.what()); }
}go deeper
Know that a class must inherit enable_shared_from_this to get a shared_ptr to itself, and that wrapping this in a new shared_ptr is a bug.
Explain the second control block, the hidden weak_ptr that the first owner fills in, and the cases where shared_from_this() throws.
Design async objects around it: factory-only creation, a start() member, strong captures for in-flight I/O and weak captures for optional callbacks.
Treat enable_shared_from_this as a sign that an object's lifetime is decided by callbacks, and make sure that is a deliberate design choice.
## The problem: an object that needs a shared_ptr to itself In an asynchronous server, a `Session` starts a read and registers a callback that will run later on the I/O loop. If the registry drops the session meanwhile, the callback must not touch a destroyed object, so the callback should **co-own** the session. Inside a member function the session only has `this`, a raw pointer, and the obvious attempt is wrong: ```cpp void Session::start_read() { auto self = std::shared_ptr<Session>(this); // second control block pending_io.push_back([self] { /* ... */ }); } ``` Every `shared_ptr` constructor that takes a raw pointer creates a **new control block** with its own count. The registry's group and the callback's group know nothing of each other; the first to reach zero deletes the session, and the second deletes it again — a double delete that AddressSanitizer reports as `attempting double-free`. ## How enable_shared_from_this solves it `std::enable_shared_from_this<T>` is a base class template holding an exposition-only `weak_ptr<T>` member, *weak-this*. The standard says that when a `shared_ptr` constructor takes ownership of a pointer whose type has an **unambiguous and accessible** base that is a specialization of `enable_shared_from_this`, it assigns itself to *weak-this* if that is still expired. `make_shared` and `allocate_shared` do the same. Afterwards: - `shared_from_this()` returns `shared_ptr<T>(weak-this)` — a new owner in the **existing** group; - `weak_from_this()` (C++17) returns *weak-this* itself, a non-owning observer. ```cpp class Session : public std::enable_shared_from_this<Session> { /* ... */ }; auto self = shared_from_this(); // same control block as the registry ``` ## When shared_from_this() throws Because it constructs a `shared_ptr` from a `weak_ptr`, `shared_from_this()` throws `std::bad_weak_ptr` whenever *weak-this* is empty. Since C++17 (paper P0033R1, "Re-enabling shared_from_this") that is the specified behaviour; before C++17 calling it on an object without an owner was a precondition violation, i.e. undefined behaviour. The cases: 1. **Inside the constructor.** No `shared_ptr` owns the object yet; *weak-this* is set only after construction finishes. 2. **On an object that no `shared_ptr` owns** — a stack object, a member of another object, or one still owned by a `std::unique_ptr` (converting that `unique_ptr` to a `shared_ptr` later does set *weak-this*). 3. **With a private, protected or ambiguous base.** The constructor cannot see the base, silently skips the assignment, and every later call throws. The example on this page shows the private-base case throwing. 4. **After the last owner is gone** — but then the object is being destroyed, and calling into it is a bug of its own. ## Choosing between the two members in callbacks | callback | capture | effect | |---|---|---| | in-flight read or write whose completion must find the session | `self = shared_from_this()` | the session lives until the callback runs | | timer, presence update or retry that is pointless once the user left | `weak = weak_from_this()`, then `lock()` | the callback does nothing if the session is gone | A callback that is stored indefinitely and captures `shared_from_this()` creates a cycle through the session's own members; prefer the weak capture there. ## A factory that enforces the rule The safest design makes it impossible to create a session that no `shared_ptr` owns: ```cpp class Session : public std::enable_shared_from_this<Session> { public: static std::shared_ptr<Session> create(std::string user) { return std::shared_ptr<Session>(new Session(std::move(user))); } void start(); // registers callbacks; safe to call shared_from_this() private: explicit Session(std::string user); }; ``` The constructor is private, so stack objects and `unique_ptr` owners cannot be created from outside the class, and every instance is connected to its owner group from birth. The factory writes `new` itself because `std::make_shared` cannot reach a private constructor; giving up the single allocation is usually a fair price for the guarantee. ## Rules that keep it safe - Inherit **publicly**: `class Session : public std::enable_shared_from_this<Session>`. - Create sessions only through `std::make_shared` or a factory that returns `std::shared_ptr` (a private constructor plus a static `create()` enforces it). - Never call `shared_from_this()` from a constructor; register callbacks in a `start()` member called after creation. - Never capture raw `this` in a callback that can outlive the call.
- Why does calling shared_from_this() in the constructor throw?During construction no `shared_ptr` owns the object yet: `make_shared` or the `shared_ptr` constructor fills the hidden `weak_ptr` only after the object's constructor returns. So `shared_from_this()` finds an empty `weak_ptr` and throws `std::bad_weak_ptr`. Register callbacks from a `start()` member, or from a static factory that creates the `shared_ptr` first and then calls into the object.
- When should a callback capture weak_from_this() instead of shared_from_this()?When the callback must not extend the session's life, such as a timer or presence notification that is pointless once the user has gone. It calls `lock()` and returns if the result is empty. `shared_from_this()` suits in-flight I/O whose completion must find the session, but a callback stored indefinitely that captures it keeps the session alive through its own members.
- shared_ptr<T>(this) is fine as long as the object came from make_shared
- shared_from_this() works in the constructor once the base is initialized
- Inheriting enable_shared_from_this privately is enough
- shared_from_this() returns a weak_ptr
- Capturing raw this in an async callback is safe while a registry holds the session