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);
}