相关疑难解决方法(0)

weak_ptr如何知道共享资源已过期?

考虑以下代码:

#include <memory>
#include <iostream>

using namespace std;

struct MySharedStruct
{
  int i;
};

void print_value_of_i(weak_ptr<MySharedStruct> weakPtr)
{
  if (shared_ptr<MySharedStruct> sp = weakPtr.lock())
  { cout << "Value of i = " << sp->i << endl; }
  else
  { cout << "Resource has expired"; }
}

int main()
{
  shared_ptr<MySharedStruct> sharedPtr(new MySharedStruct() );
  sharedPtr->i = 5;

  weak_ptr<MySharedStruct> weakPtr;
  weakPtr = sharedPtr;

  print_value_of_i(weakPtr);

  sharedPtr.reset(new MySharedStruct() ); // <<----- How does weak_ptr know it has expired after this line executes?
  sharedPtr->i = 10; …
Run Code Online (Sandbox Code Playgroud)

c++ smart-pointers refcounting shared-ptr weak-ptr

11
推荐指数
2
解决办法
3938
查看次数

标签 统计

c++ ×1

refcounting ×1

shared-ptr ×1

smart-pointers ×1

weak-ptr ×1