Is there a weak_ptr equivalent for shared_from_this?

I have a class that I know will always belong std::shared_ptr. However, the transfer, shared_ptror even weak_ptrfunctions and methods that do not require property rights or lifetime guarantees, creates unnecessary overhead. To get around this, I often pass in source function pointers. The class itself is inherited from std::enable_shared_from_this, therefore, if the function should take responsibility for the pointer, it can use the class method to get it shared_ptr.

All of this works great. However, there are cases when I do not want to make shared_ptrfrom a raw pointer, instead I want to weak_ptr.

From what I understand about a regular implementation std::shared_ptr, it has two atomic variables used as reference counters; one for shared_ptr, one for weak_ptr.

If all I have is a raw pointer to my class and I want weak_ptr, I must first create shared_ptrand convert it. This means that link counts are changed as follows:

  • Construct shared_ptr, increment shared_ptrcounter
  • Copy construct weak_ptr, increment weak_ptrcounter
  • Allow shared_ptrout of scope, decrease shared_ptrcounter

This seems to contradict the idea that "you are not paying for what you are not using." Is there a way for my class to simply provide weak_ptrwithout first creating it shared_ptr?

+4
3

weak_ptr shared_ptr?

; , enable_shared_from_this, shared_ptr. enable_shared_from_this weak_ptr. , .

, ++ 17 weak_ptr enable_shared_from_this.

+5

P0033 ++ 17 2015 , weak_from_this , std::enable_shared_from_this.

+7

It is almost so trivial to realize that it is not worth inserting into 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();
}
+3
source

All Articles