【16】c++11新特性 —>弱引用智能指针weak

编程入门 行业动态 更新时间:2024-10-26 02:34:00

【16】c++11新特性 —>弱引用智能<a href=https://www.elefans.com/category/jswz/34/1768268.html style=指针weak"/>

【16】c++11新特性 —>弱引用智能指针weak

定义

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

use_count

#include <iostream>
#include <memory>
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;
}

expired()

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

#include <iostream>
#include <memory>
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;
}


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

lock

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

#include <iostream>
#include <memory>
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;
}

reset

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

#include <iostream>
#include <memory>
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;
}

更多推荐

【16】c++11新特性 —>弱引用智能指针weak

本文发布于:2023-11-15 21:53:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1606915.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   新特性   智能   weak

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!