C++解决share_ptr造成的循环引用

参考链接:https://blog.csdn.net/yc2zgh1314/article/details/51264963

     https://www.cnblogs.com/duacai/p/13341422.html

先看有循环引用问题的代码:

#include<iostream>
using namespace std;
 
struct Node
{
    shared_ptr<Node> _pre;
    shared_ptr<Node> _next;
 
    ~Node()
    {
        cout << "~Node():" << this << endl;
    }
    int data;
};
 
void FunTest()
{
    shared_ptr<Node> Node1(new Node);
    shared_ptr<Node> Node2(new Node);
    Node1->_next = Node2;
    Node2->_pre = Node1;
 
    cout << "Node1.use_count:"<<Node1.use_count() << endl;
    cout << "Node2.use_count:"<< Node2.use_count() << endl;
}
 
int main()
{
    FunTest();
    system("pause");
    return 0;
}

结果(没有释放分配的堆内存):

程序模型图:

出现堆内存没有释放的原因是:

两个堆空间没有释放是因为指向它们的智能指针成员变量没有析构导致引用计数不为0,这个智能指针成员变量没有析构又是因为它们所属的堆对象没有析构,而这两个堆对象没有析构是因为它们被智能指针保管,该智能指针又被指向的堆对象的智能指针成员变量增加了引用计数。

解决的办法就是用weak_ptr取代智能指针成员变量,从而解决shared_ptr智能指针循环引用的问题。

代码:

#include<memory>
#include<iostream>
using namespace std;
 
struct Node
{
    weak_ptr<Node> _pre;
    weak_ptr<Node> _next;
 
    ~Node()
    {
        cout << "~Node():" << this << endl;
    }
    int data;
};
 
void FunTest()
{
    shared_ptr<Node> Node1(new Node);
    shared_ptr<Node> Node2(new Node);
    Node1->_next = Node2;
    Node2->_pre = Node1;
 
    cout <<"Node1.use_count:"<< Node1.use_count() << endl;
    cout <<"Node2.use_count:"<< Node2.use_count() << endl;
}
 
int main()
{
    FunTest();
    system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/kongbursi-2292702937/p/15689971.html