C++11:20weak_ptr弱引用的智能指针
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C++11:20weak_ptr弱引用的智能指针,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1731字,纯文字阅读大概需要3分钟。
内容图文
![C++11:20weak_ptr弱引用的智能指针](/upload/InfoBanner/zyjiaocheng/631/b76b5725273a46118473642a52496d42.jpg)
20、weak_ptr弱引用的智能指针
0、课前秀
- 弱引用指针weak_ptr是用来监视shared_ptr的,不会使引用计数加1,它不管理shared_ptr内部的指针,主要是为了监视shared_ptr的生命周期。
- weak_ptr没有重载操作符
*
和->
,因为它不共享指针,不能操作资源。 - weak_ptr还可以用来返回this指针和解决循环引用的问题。
1、weak_ptr基本用法
- (1)通过use_count()方法来获得当前观测资源的引用计数
shared_ptr<int> sp(new int(10));
weak_ptr<int> wp(sp);
cout<<wp.use_count()<<endl; //结果将输出1
- (2)通过expired()方法来判断所观测的资源是否已经被释放
shared_ptr<int> sp(new int(10));
weak_ptr<int> wp(sp);
if(wp.expired())
std::cout << "weak_ptr无效,所监视的智能指针已被释放\n";
else
std::cout << "weak_ptr有效\n";
//结果将输出:weak_ptr有效
- (3)通过lock方法来获取所监视的shared_ptr
std::weak_ptr<int> gw;
void f()
{
if(gw.expired()) //所监视的shared_ptr是否释放
{
std::cout << "gw is expired\n";
}
else
{
auto spt = gw.lock();
std::cout << *spt << "\n";
}
}
int main()
{
{
auto sp = std::make_shared<int>(42);
gw = sp;
f();
}
f();
}
/*
输出:
42
gw is expired
*/
2、weak_ptr返回this指针
- 代码
struct A: public std::enable_shared_from_this<A>
{
std::shared_ptr<A> GetSelf()
{
return shared_from_this();
}
~S()
{
cout<<"A is deleted"<<endl;
}
};
std::shared_ptr<A> spy(new A);
std::shared_ptr<A> p = spy->GetSelf();//OK
/*
输出结果
A is deleted
*/
3、weak_ptr解决循环引用问题
- 代码
struct A;
struct B;
struct A{
std::shared_ptr<B> bptr;
~A() {cout<<"A is deleted!"<<endl;}
};
struct B{
std::shared_ptr<A> aptr;//将A B中的任何一个改成 weak_ptr
~B() {cout<<"B is deleted!"<<endl;}
};
void TestPtr()
{
{
std::shared_ptr<A> ap(new A);
std::shared_ptr<B> bp(new B);
ap->bptr = bp;
bp->aptr = ap;
}//Objects should be destroyed
}
ReadMe
- 20200525上班期间开了个头,看了一点点,晚上回来后整理起来的,基本没有串起的,只是个记录,后面再看呢。
内容总结
以上是互联网集市为您收集整理的C++11:20weak_ptr弱引用的智能指针全部内容,希望文章能够帮你解决C++11:20weak_ptr弱引用的智能指针所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。