理解 Shared_ptr 与循环引用?

Understanding Shared_ptr with cyclic references?

我想了解 shared_ptr 增加或减少引用计数的方式?

 #include <iostream>
 #include <memory>

class B;

class A
{
  public:
  std::shared_ptr<B> b_ptr_;
};

class B
{
  public: 
  std::shared_ptr<A> a_ptr_;
};

void func(std::shared_ptr<A> &aptr)
{
  std::shared_ptr<B> bptr = std::make_shared<B>(); //Creating shared pointer
  bptr->a_ptr_ = aptr; // Creating cyclic dependency 
  aptr->b_ptr_ = bptr;

  std::cout<<"\nFunc::a_ptr_ use_count = "<<bptr->a_ptr_.use_count();
  std::cout<<"\nFunc::b_ptr_ use_count = "<<aptr->b_ptr_.use_count();     
}

int main()
{
  std::shared_ptr<A> aptr = std::make_shared<A>();
  std::cout<<"\nBefore func::a_ptr_ use_count = "<<aptr.use_count();
  func(aptr);
  std::cout<<"\nAfter func::a_ptr_ use_count = "<<aptr.use_count();
  std::cout<<"\nAfter func::b_ptr_ use_count = "<<aptr->b_ptr_.use_count();
  return 0;   
}

Output: 
This is the output I see:
Before func::a_ptr_ use_count = 1
Func::a_ptr_ use_count = 2
Func::b_ptr_ use_count = 2
After func::a_ptr_ use_count = 2
After func::b_ptr_ use_count = 1

然而我在期待这个 "After func::a_ptr_ use_count = 1"。在 bptr 超出 func() 的范围后,引用计数应该已经减少。 我在这里错过了什么?

提到的重复问题没有解释引用计数如何 incremented/decremented。我对如何完成此操作的内部机制更感兴趣(在 shared_ptr 中),这在所附的其他问题的答案中没有解释。

为什么引用计数应该减少? bptr 可能超出范围,但 bptr 只会影响 B 对象的引用计数。还有两个对您的 A 对象的引用:

  1. 共享指针仍在 main
  2. 范围内
  3. 存储在您的 B 对象中的共享指针

只要存在对您的 A 对象的实时引用,您的 B 对象就会继续存在,反之亦然(这是您通过循环共享引用有意触发的)。要使您的 B 对象消失,您需要在引用循环中有一个引用为 weak/raw,并清除存储在您的 main 方法中的指针,这样就不会保留顶级引用。