• 【C++智能指针】(面试)使用my_weak_ptr解决循环引用问题


    代码实例:

    class Child;
    class Parent
    {
    public:
    	my_weak_ptr<Child> c;
    	Parent() { cout << "Parent" << endl; }
    	~Parent() { cout << "~Parent" << endl; }
    	void hi1() { cout << "Hello Parent" << endl; }
    };
    class Child
    {
    public:
    	my_weak_ptr<Parent> p;
    	Child() { cout << "Child" << endl; }
    	~Child() { cout << "~Child" << endl; }
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    int main()
    {
    	my_shared_ptr<Parent> parent(new Parent());
    	my_shared_ptr<Child>child(new Child());
    	parent->c = child;
    	child->p = parent;
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    ## 构造两个对象
    ~my_shared_ptr()  
    	{
    		if (Rep != nullptr && --Rep->_Uses == 0)
    		{                         //在析构的时候不仅要减强引用个数还要减弱引用个数
    			_mDeletor(_Ptr);   
    			if (--Rep->_Weaks == 0)
    			{
    				delete Rep;
    			}
    		}
    		_Ptr = nullptr;
    		Rep = nullptr;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    ~my_weak_ptr()
    	{
    		if (_Rep != nullptr)  //弱引用只能析构计数
    		{
    			delete _Rep;
    		}
    		_Rep = nu
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    llptr;
    }

    my_shared_ptr<Parent> parent(new Parent());
    	my_shared_ptr<Child>child(new Child());
    
    • 1
    • 2

    请添加图片描述

    相互引用

    parent->c = child;
    child->p = parent;
    
    • 1
    • 2

    请添加图片描述

    析构的过程

    由于child对象时后创建的所以,先析构child
    1.先判断_Rep是否为空,以及----Rep->_Uses 是否等于0,如果是,这个时候要析构_Ptr指向的child对象。
    2.这个对象有weak_ptr的对象成员c,c中的rep指向parent的引用计数结构,所以在销毁c对象前要对parent中_weaks减一。
    3.接下来回退到child对象,将child的引用计数结构中的_weaks减一,若_weaks为0,则将child的引用计数结构析构掉,否则,回退到child,将其_ptr和_Rep均置为空。
    请添加图片描述

    接下来析构parent

    1.判断parent中的_Rep是否为空,以及引用计数类型中的_Uses减一是否为0,如果为0,删除parent中_Parent指针所指的parent对象,由于parent中有weak_ptr的对象c,c中有_Rep指针,指向child对象中_Rep指向所指的引用计数结构。
    2.判断其_Rep是否为空,以及对其_weaks减一,如为0,则析构掉这个引用计数结构。
    3.回退到c对象,在回退到parent对象,将c对象析构掉。
    4.再判断parent中Rep所指的引用计数结构中的_weaks减一是否为0,如果为0,析构掉引用计数结构。
    4.最后将parent中的ptr和Rep置为空
    请添加图片描述
    请添加图片描述

    请添加图片描述

    总结

    parent释放了 两个引用结构和Parent类的对象
    child只是释放了Child类的对象

  • 相关阅读:
    vue3的路由配置
    mycat 常用分片规则使用详解
    网址打包微信小程序源码 wap转微信小程序 网站转小程序源码 网址转小程序开发
    Pulsar Meetup 深圳 2024 会务介绍
    阿里云docker容器服务器安装nextcloud步骤
    ELK8.4安装配置错误记录
    C++入门精讲——入门看完这一篇就够了
    Go module快速上手
    一文详解KMP
    Pytorch基础:Tensor的reshape方法
  • 原文地址:https://blog.csdn.net/weixin_52958292/article/details/127692112