智能指针的使用和原理

weak_ptr是为了配合shared_ptr而引入的一种智能指针
它不具有普通指针的行为,没有重载operator*和->,它的最大作用在于协助shared_ptr工作,像旁观者那样观测资源的使用情况

  1. weak_ptr可以从一个shared_ptr或者另一个weak_ptr对象构造,获得资源的观测权。
  2. weak_ptr没有共享资源,它的构造不会引起指针引用计数的增加                                                                                                 
  3. 使用weak_ptr的成员函数use_count()可以观测资源的引用计数,成员函数expired()的功能等价于use_count()==0,但更快,表示被观测的资源(也就是shared_ptr的管理的资源)已经不复存在
#include <iostream>
#include <memory>

int main() 
{
	std::shared_ptr<int> sh_ptr = std::make_shared<int>(10);
	std::shared_ptr<int> sh_ptr1(sh_ptr);
	std::cout << sh_ptr.use_count() << std::endl; //2

	std::weak_ptr<int> wp(sh_ptr);
	/*弱指针的use_count,获取shared_ptr的引用数量*/
	std::cout << wp.use_count() << std::endl;     //2

	if (!wp.expired()) {
		/*lock()从被观测的shared_ptr获得一个可用的shared_ptr对象, 从而操作资源*/
		//std::shared_ptr<int> sh_ptr2 = wp; //error:不能从弱指针转换为shard_ptr
		std::shared_ptr<int> sh_ptr2 = wp.lock(); 
		std::cout << wp.use_count() << std::endl; //3
		*sh_ptr2 = 100;
			
		std::cout << *(wp.lock()) << std::endl;   //100
		std::cout << wp.use_count() << std::endl; //3
	}
	
	//delete memory
}

 

参考

https://www.cnblogs.com/wxquare/p/4759020.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值