auto main555() -> std::shared_ptr<A01>
{
std::shared_ptr<A01> ptr = std::make_shared<A01>(); //usercount: 1
auto sec = ptr; //usercount: 2
auto third = ptr; //usercount: 3
return third; //
}
返回third的时候调用:
shared_ptr(shared_ptr&& _Right) noexcept
{ // construct shared_ptr object that takes resource from _Right
this->_Move_construct_from(_STD move(_Right));
}
template<class _Ty2>
void _Move_construct_from(_Ptr_base<_Ty2>&& _Right)
{ // implement shared_ptr's (converting) move ctor and weak_ptr's move ctor
_Ptr = _Right._Ptr;
_Rep = _Right._Rep;
_Right._Ptr = nullptr;
_Right._Rep = nullptr;
}
shared_ptr初始化(非空指针)的时候,默认的计数就是1。
相当于:std::shared_ptr<A01> ptr = main555();中用third初始化ptr,
调用的右值构造函数。其中_Right就是third,move之后,third里面都是空的了。然后thir里
的内容就移动到ptr了。
然后third析构,但里面没东西了,所以计数器不用减1
然后sec析构,此时usercount变为2
然后main555里的第一个变量ptr析构,usercount变为1
所以std::shared_ptr<A01> ptr = main555();这条语句,得到的ptr的usercount就是1
其实,如果没有右值构造函数,计数应该也是1,传出来的时候加1,自己析构再减1.
调用:
std::shared_ptr<A01> ptr = main555();
std::cout << ptr.use_count() << std::endl; // usercount: 1
return 1;
函数中返回shared_ptr时发生了什么。右值构造函数,以及对计数的影响。
于 2024-06-04 00:30:54 首次发布