标准库里的weak_ptr如何解决循环引用所带来的问题

#include#include#includeusing namespace std;templateclass T>class Node{public: Node(T num) :value(num) { } ~Node() { cout "~Node()" << endl; } weak_
摘要由CSDN通过智能技术生成

使用weak_ptr解决循环引用的方法

#include<iostream>
#include<memory>
#include<stdlib.h>
using namespace std;
template<class T>
class Node
{
public:
    Node(T num)
        :value(num)
    {

    }
    ~Node()
    {
        cout << "~Node()" << endl;
    }
    weak_ptr<Node> pNext; //使用弱引用打破循环引用
    weak_ptr<Node> pPre;
    T value;
};
void FunTest()
{
    shared_ptr<Node<int>> p1(new Node<int>(1));
    shared_ptr<Node<int>> p2(new Node<int>(2));
    p1->pNext = p2;
    p2->pPre = p1;
}
int main()
{
    FunTest();
    system("pause");
    return 0;
}

下面重点剖析C++标准库中的具体操作
要new出一个对象的空间那么先去调用构造函数再来使用operator new 开辟空间:

new Node<int>(1) 先去调用Node的构造函数由于类里有weak_ptr的对象因此也要调用weak_ptr的构造
weak_ptr<Node> pNext;
weak_ptr<Node> pPre;
那么也要首先pNext构造出来:调用weak_ptr的构造函数
class weak_ptr: public _Ptr_base<_Ty>  继承自_Ptr_base自然要调用_Ptr_base的构造函数
weak_ptr() _NOEXCEPT
    {   // construct empty weak_ptr object
    }
    _Ptr_base()
    : _Ptr(0), _Rep(0)
    {   // construct
    }
   _Ptr_base类里的数据成员
   _Ty *_Ptr;  //原生态指针管理结点的空间
   _Ref_count_base *_Rep;  //管理引用计数的空间

构造pPre也是同理
将weak_ptr的对象构造完成之后,此时结点构造完成之后再将这个结点交给shared_ptr这个对象去管理
调用shared_ptr的构造函数

explicit shared_ptr(_Ux *_Px)
        {   // construct shared_ptr object that owns _Px
        _Resetp(_Px);
        }
shared_ptr继承_Ptr_base()因此也会去调用_Ptr_base的构造函数 
_Ptr_base()
        : _Ptr(0), _Rep(0)
        {   // construct
        }

调用完构造函数之后在执行shared_ptr中的_Resetp(_Px)函数,
进入_Resetp(_Px)这个函数

    void _Resetp(_Ux *_Px)
        {   // release, take ownership of _Px
        _TRY_BEGIN  // allocate control block and reset
        _Resetp0(_Px, new _Ref_count<_Ux>(_Px));
        _CATCH_ALL  // allocation fai
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值