Skip to content

Advanced Gotchas

The shared_from_this With No Owner

enabling the feature does not establish ownership

struct Session : std::enable_shared_from_this<Session> {
  std::shared_ptr<Session> share() { return shared_from_this(); }
};

int main() {
  Session session;

  try {
    session.share();
  } catch (const std::bad_weak_ptr&) {
    std::cout << "no owner\n";
  }
}

Run it. Does share() create the first shared_ptr?

Answer
no owner

It throws instead of inventing an owner.

Why

std::enable_shared_from_this can find an existing shared_ptr control block; it cannot create one. A stack-allocated Session has never been adopted by a shared_ptr, so its internal weak pointer is empty and shared_from_this() throws std::bad_weak_ptr. That throw is C++17's doing; before it, calling this with no owner was undefined behavior. GCC emits no warning under -Wall -Wextra.

The fix

Establish shared ownership before calling the member:

auto session = std::make_shared<Session>();
auto another_owner = session->share();

Takeaway: shared_from_this() shares an owner that already exists; it never creates one.

Try it: g++ -std=c++17 main.cpp -o demo && ./demo

Open in Compiler Explorer ↗ Quiz this entry