小编Art*_*yan的帖子

从weak_from_this() 得到的weak_ptr 无效

这是重现的最小示例:

源代码:

#include <memory>
#include <iostream>

class A : public std::enable_shared_from_this<A>
{
 public:
  A(std::weak_ptr<A> up) : up_(up)
  {
    std::cout << "A" << " has up_? " <<
        ((up_.lock()) ? "yes" : "no")
              << std::endl;
  }

  void grow()
  {
    if (dp_)
      dp_->grow();
    else
      dp_ = std::make_shared<A>(weak_from_this());
  }

 private:
  std::weak_ptr<A> up_;
  std::shared_ptr<A> dp_;
};

int main()
{
  auto wp = std::weak_ptr<A>();
  A a(wp);
  for (int i = 0; i < 3; ++i)
  {
    a.grow();
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

原始日志:

clang++ minimal.cpp && …
Run Code Online (Sandbox Code Playgroud)

c++ smart-pointers weak-ptr

2
推荐指数
1
解决办法
213
查看次数

标签 统计

c++ ×1

smart-pointers ×1

weak-ptr ×1