是shared_ptr的构造函数,还是operator =

class A01 {
public:
    //std::weak_ptr<B0> b_ptr;
    int data{ 1234 };
    ~A01() {
        std::cout << "A01 deleted\n";
    }
    void Print() { std::cout << "I'm A01\n"; }
};
 

 
auto main444() -> int
{
    std::shared_ptr<A01> ptr = std::make_shared<A01>(); //ptr:1, ctrl_block:1
    auto sec = ptr;   //这一步调用的哪个函数
    return 1;
} 
 
int main()
{
    main444();
    return 1;
}

 auto sec = ptr;   //这一步调用的哪个函数?

答案是:

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

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

class A01 {
public:
    //std::weak_ptr<B0> b_ptr;
    int data{ 1234 };
    ~A01() {
        std::cout << "A01 deleted\n";
    }
    void Print() { std::cout << "I'm A01\n"; }
};
 

 
auto main444() -> int
{
    std::shared_ptr<A01> ptr = std::make_shared<A01>(); //ptr:1, ctrl_block:1
    std::shared_ptr<A01> sec ;
    sec = ptr;   //这一步调用的哪个函数
    return 1;
} 
 
int main()
{
    main444();
    return 1;
}

 sec = ptr;调用哪个?

见下面:

	shared_ptr& operator=(const shared_ptr& _Right) noexcept
		{	// assign shared ownership of resource owned by _Right
		shared_ptr(_Right).swap(*this); //在swap之前,this所指向的控制块为NULL,所以临时shared_ptr对象在析构时,并不会对计数减1。所以此行结束之后,整体计数器加1
		return (*this);
		}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值