boost shared_ptr: difference between operator= and reset?

前端 未结 4 1372
眼角桃花
眼角桃花 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:18

    operator= takes another shared_ptr as a parameter thus creating another copy (and upping the reference count) while reset() takes a pointer and optionally a deleter, thus in reality creating a new shared_ptr on top of the current one.

    reset is equivalent to (and probably implemented as)

    void reset(T p, D d)
    {
       shared_ptr shared(p,d);
       swap( shared );
    }
    

    operator= is likely to be implemented as:

    shared_ptr& operator=( shared_ptr const& other )
    {
       shared_ptr shared(other);
       swap(other);
       return *this;
    }
    

    The two functions are similar in that they release control of what they are already containing, if any, and manage a different pointer instead.

提交回复
热议问题