boost shared_ptr: difference between operator= and reset?

前端 未结 4 1367
眼角桃花
眼角桃花 2021-02-13 22:55

Are there any differences between the two pieces of code below? Is any of them preferable to the other?

operator=

boost::shared_ptr&         


        
4条回答
  •  粉色の甜心
    2021-02-13 23:11

    Assignment operator create a new shared object from existing one, incrementing the reference count

    CSharedObj& CSharedObj::operator=(CSharedObj& r) noexcept
    { 
         if(*this != r){
            //detach from the previous ownership
            if(0 == dec()) delete m_pControlObj;
            //attach to the new control object and increment the reference count
            r.inc();
            m_pControlObj = r.m_pControlObj;
        }
        return *this;
    }
    

    while the reset call doesn't create the new shared object, but rather a new ownership - attaching to the new underlying pointee ( via control object)

    void CSharedObj::reset(Ptr pointee) noexcept
    {
       //check if this is a last reference-detach from the previous ownership
       if(0==dec()) delete m_pControlObj;
       // create the ownership over the new pointee (refCnt = 1)
       m_pControlObj = new (std::nothrow) CControlObj(pointee);
    }
    

提交回复
热议问题