我知道如何使用weak_ptr
,我阅读了以下文章:
About “circular reference”, I used weak_ptr but memory leak still happened
但是有一个我无法理解的概念。
据我所知,我将演示shared_ptr
的创建和发布:
shared_ptr
pa
已创建reference_count
的[pa
应为0
。因为没有shared_ptr
指向pa
。
{/*scope 1*/
shared_ptr<int> pa;
// reference_count_pa = 0
}
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
。
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
scope 2
的末尾>[pb
被删除,因为程序从scope 2
中移出。
reference_count
的[pa
现在是0
,因为没有shared_ptr
指向pa
。
reference_count
的[pb
仍然是1
。
scope 1
的末尾>C0]的[reference_count
现在是pb
,因为没有0
指向shared_ptr
。
上述步骤据我所知是reference_count。
[pb
和pa
被正常删除。
我很困惑。
任何人都可以通过上述步骤纠正我的错误吗?
谢谢!
我知道如何使用weak_ptr,我读了以下文章:关于“循环引用”,我使用了weak_ptr,但是仍然发生内存泄漏,但是有一个我还不了解的概念。我将演示...
有人在上述步骤中纠正了我的错误吗?
[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中找到。