关于C ++中引用计数和循环引用的概念

问题描述 投票:0回答:2

我知道如何使用weak_ptr,我阅读了以下文章:

About “circular reference”, I used weak_ptr but memory leak still happened

但是有一个我无法理解的概念。

据我所知,我将演示shared_ptr的创建和发布:


1。shared_ptrpa已创建

reference_count的[pa应为0。因为没有shared_ptr指向pa

{/*scope 1*/

  shared_ptr<int> pa;
  // reference_count_pa = 0
}

2。我将新的shared_ptr<int> pb分配给另一个范围中的pa

{/*scope 1*/

  shared_ptr<int> pa;

  {/*scope 2*/

    shared_ptr<int> pb = pa;
    // reference_count_pa = 1
    // reference_count_pb = 0
  }
}

reference_count的[pa应为1,因为shared_ptr pb指向pa

reference_count的[pb应该为0,因为没有shared_ptr指向pb

3。现在,一个简单的Circular Reference

About “circular reference”, I used weak_ptr but memory leak still happened中所示:

{/*scope 1*/

  shared_ptr<int> pa;

  {/*scope 2*/

    shared_ptr<int> pb = pa;
    pa = pb; //circular reference
    // reference_count_pa = 1
    // reference_count_pb = 1
  }
}

reference_count的[pa应为1,因为shared_ptr pb指向pa

reference_count的[pb应为1,因为shared_ptr pa指向pb

4。在scope 2的末尾>

[pb被删除,因为程序从scope 2中移出。

reference_count的[pa现在是0,因为没有shared_ptr指向pa

reference_count的[pb仍然是1

5。在scope 1的末尾>

C0]的[reference_count现在是pb,因为没有0指向shared_ptr


上述步骤据我所知是reference_count。

[pbpa被正常删除。

我很困惑。

任何人都可以通过上述步骤纠正我的错误吗?

谢谢!

我知道如何使用weak_ptr,我读了以下文章:关于“循环引用”,我使用了weak_ptr,但是仍然发生内存泄漏,但是有一个我还不了解的概念。我将演示...

c++ smart-pointers circular-reference
2个回答
2
投票

有人在上述步骤中纠正了我的错误吗?


0
投票

[W0]是指您写struct Node { std::shared_ptr<Node> next; }; int main() { std::shared_ptr<Node> a = std::make_shared<Node>(); std::shared_ptr<Node> b = std::make_shared<Node>(); a->next = b; b->next = a; } 时的意思吗?后者不能在cpp-reference中找到。

© www.soinside.com 2019 - 2024. All rights reserved.