• 【16】c++11新特性 —>弱引用智能指针weak_ptr(1)


    定义

    std::weak_ptr:弱引用的智能指针,它不共享指针,不能操作资源,是用来监视 shared_ptr 中管理的资源是否存在。

    use_count

    #include 
    #include 
    using namespace std;
    
    int main()
    {
    	shared_ptr<int>sp(new int);
    	weak_ptr<int>wp1;
    	wp1 = sp;
    
    	cout << "use_count : " << wp1.use_count() << endl;
    	cout << "use_count : " << sp.use_count() << endl;
    
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    在这里插入图片描述

    expired()

    通过调用std::weak_ptr类提供的expired()方法来判断观测的资源是否已经被释放.

    #include 
    #include 
    using namespace std;
    
    int main()
    {
    	shared_ptr<int>sp(new int);
    	weak_ptr<int>wp(sp);
    	cout << "1.wp " << (wp.expired() ? "is" : "is not ") << "expired" << endl;
    	sp.reset();
    	cout << "2.wp " << (wp.expired() ? "is" : "is not ") << "expired" << endl;
    
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    在这里插入图片描述
    weak_ptr监测的就是shared_ptr管理的资源,当共享智能指针调用shared.reset();之后管理的资源被释放,因此weak.expired()函数的结果返回true,表示监测的资源已经不存在了。

    lock

    通过调用std::weak_ptr类提供的lock()方法来获取管理所监测资源的shared_ptr对象:

    #include 
    #include 
    using namespace std;
    
    int main()
    {
    	shared_ptr<int>sp(new int(10));
    	shared_ptr<int>sp1;
    	weak_ptr<int>wp(sp);
    	sp1 = wp.lock(); //sp和sp1共享同一个资源
    	cout << "sp1: use_count" << sp1.use_count() << endl;
    	sp.reset();
    	cout << "sp1:" << *sp1 << endl;
    
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    在这里插入图片描述

    reset

    通过调用std::weak_ptr类提供的reset()方法来清空对象,使其不监测任何资源

    #include 
    #include 
    using namespace std;
    
    int main()
    {
    	shared_ptr<int>sp(new int(10));
    	shared_ptr<int>sp1;
    	weak_ptr<int>wp(sp);
    	sp1 = wp.lock(); //sp和sp1共享同一个资源
    	cout << "sp1" << sp1.use_count() << endl;
    	cout << "wp:" << wp.use_count() << endl;
    	sp.reset();
    	cout << "sp1:" << *sp1 << endl;
    	wp.reset(); //清空对象
    	cout << "wp:" << wp.use_count()<< endl;
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    在这里插入图片描述

  • 相关阅读:
    户外led显示屏中的裸眼3D效果是怎么做出来的?
    Azure Kinect微软摄像头Unity开发小结
    【Python脚本进阶】2.2、构建一个SSH僵尸网络(中):用Pxssh暴力破解SSH密码
    OSError: Can‘t load tokenizer for ‘bert-base-chinese‘
    黑客入狱知识点总结
    Spring 源码(1)Spring IOC Bean 创建的整体流程
    20220705开发板BL602的SDK编译以及刷机
    Vue中动态Class实战
    pandas学习(五)merge
    队列和栈两种数据结构的区别和Python实现
  • 原文地址:https://blog.csdn.net/weixin_42097108/article/details/134293938