std::shared_ptr: reset() vs. assignment

后端 未结 4 1377
小鲜肉
小鲜肉 2021-02-04 23:58

This is a basic question, but I did not find a previous post about it. The title of the following question sounds like it might be the same question as mine, but the question it

4条回答
  •  借酒劲吻你
    2021-02-05 00:09

    reset() changes the managed object of an existing shared_ptr.

    p = std::shared_ptr(new int(5)); and p.reset(new int(5));

    The former involves creating a new shared_ptr and moving it into a variable. The latter does not create a new object, it simply changes the underlying pointer in managed by the shared_ptr.

    Put another way the two are meant to be used in different cases. Assignment is for when you have a shared_ptr and reset for when you have a raw pointer.

    Another thing to keep in mind is that shared_ptr was available in boost before move assignment existed and influenced the latest version heavily. Without move assignment being able to change a shared_ptr without making a copy is beneficial as it saves you the bookkeeping of the extra object.

提交回复
热议问题