C++11 weak_ptr


#include "pch.h"
#include <iostream>

using namespace std;

weak_ptr<int> gw;
void f()
{
	if (gw.expired())
	{
		cout << "gw is expired\n";
	}
	else
	{
		auto spt = gw.lock();
		cout << *spt << endl;
	}
}
int main()
{
   /*
	弱引用指针weak_ptr是用来监视shared_ptr的,不会使引用计数加1,,它不管理shared_ptr内部的指针,
	主要是为了监视shared_ptr的生命周期,更像是shared_ptr的一个助手。
	纯粹只是作为一个旁观者来监视shared_ptr中管理的资源是否存在。	
   */
	//1.基本用法
	//1)通过use_count()方法来获得当前观测资源的引用计数
	{
		shared_ptr<int> sp(new int(10));
		weak_ptr<int> sw(sp);
		cout << sw.use_count() << endl;
	}
	//2)通过expired()方法来判断所观测的资源是否已经释放
	{
		shared_ptr<int> sp(new int(10));
		weak_ptr<int> wp(sp);
		if (wp.expired())
		{
			cout << "weak_ptr无效\n";
		}
		else
		{
			cout << "weak_ptr有效\n";
		}
				
	}
	//3)通过lock方法来获取所监视的shared_ptr
	{
		auto sp = make_shared<int>(42);
		gw = sp;
		f();
	}
	f();

	//2.weak_ptr返回this指针
	{
		struct A :public enable_shared_from_this<A>
		{
			shared_ptr<A> GetSelf()
			{
				return shared_from_this();
			}
			~A()
			{
				cout << "A is deleted" << endl;
			}
		};

		shared_ptr<A> spy(new A);
		shared_ptr<A> p = spy->GetSelf(); // OK
	}
	//3.weak_ptr解决循环引用问题
	{
		cout << "--------------------" << endl;
		struct A;
		struct B;
		struct A {
			shared_ptr<B> bptr;
			~A() {
				cout << "A is deleted!" << endl;
			}
		};

		struct B {
			weak_ptr<A> aptr;
			~B() {
				cout << "B is deleted!" << endl;
			}
		};

		{
			shared_ptr<A> ap(new A);
			shared_ptr<B> bp(new B);
			ap->bptr = bp;
			bp->aptr = ap;
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小蚂蚁_CrkRes

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值