shared_ptr的operator = 里都发生了什么

std::shared_ptr<A01> ptr = std::make_shared<A01>();
std::shared_ptr<A01> sec = ptr;
std::shared_ptr<A01> third = ptr;
std::cout << sec.use_count() << std::endl;
sec = third; //这一步的时候,计数有哪些逻辑?

 执行到最后一行代码之前时,计数为3 。

在执行最后一行时,shared_ptr(_Right).swap(*this);创建了个临时对象,这个临时对象挺巧妙的,其在创建时,会调用_Copy_construct_from,此时会把计数增加到4,然后呢,它紧接着会析构,会再把计数减到3。这一增一减,计数不变。也符合逻辑。

按照堆栈的顺序:

	
template<class _Ty2>
		void _Copy_construct_from(const shared_ptr<_Ty2>& _Other)
		{	// implement shared_ptr's (converting) copy ctor
		if (_Other._Rep)
			{
			_Other._Rep->_Incref();
			}

		_Ptr = _Other._Ptr;
		_Rep = _Other._Rep;
		}



	shared_ptr(const shared_ptr& _Other) noexcept
		{	// construct shared_ptr object that owns same resource as _Other
		this->_Copy_construct_from(_Other);
		}


	shared_ptr& operator=(const shared_ptr& _Right) noexcept
		{	// assign shared ownership of resource owned by _Right
		shared_ptr(_Right).swap(*this);
		return (*this);
		}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值