• 【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

    在这里插入图片描述

  • 相关阅读:
    几行代码轻松实现flutter 调用百度地图
    细说RTSP、RTMP和GB28181区别
    机器学习笔记 - 关于Contrastive Loss对比损失
    HTML八大特性
    Jenkins 使用 AD域登陆
    【科技素养】蓝桥杯STEMA 科技素养组模拟练习试卷2
    Docker和debezium是什么关系,如何部署?
    Flutter 渲染机制——GPU线程渲染
    自定义镜像运行Nginx及Java服务并基于NAS实现动静分离
    MindManager22全新版思维导图软件工具
  • 原文地址:https://blog.csdn.net/weixin_42097108/article/details/134293938