Is there a weak_ptr equivalent to shared_from_this?

Proposal P0033 was accepted for C++17 in the October 2015 meeting, which adds weak_from_this to classes deriving from std::enable_shared_from_this.


Is there a way for my class to just provide weak_ptr without first creating a shared_ptr?

Not in C++14; the only operation that enable_shared_from_this supports is creating a shared_ptr. Now, enable_shared_from_this should have sufficient information to construct a weak_ptr directly. But you can't do it from the outside, as the class doesn't expose its implementation details to you.

C++17 has support for fetching a weak_ptr from an enable_shared_from_this class via weak_from_this.


It's almost so trivial to implement that it's not worth putting in the library...

#include <memory>

template<class T> std::weak_ptr<T> weak_from_this(T*p) {
  return { p->shared_from_this() };
}

struct S : std::enable_shared_from_this<S>
{
  auto foo() {
    return weak_from_this(this);
  }
};


int main()
{
  auto ps = std::make_shared<S>();
  auto wps = ps->foo();
}