boost shared_ptr: difference between operator= and reset?

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

    foo.reset(p) is defined to be equivalent to shared_ptr(p).swap(foo).

    Assignment is logically equivalent to copy-and-swap, and possibly implemented that way. So foo = shared_ptr(p); is equivalent to foo.swap(shared_ptr(p)). Possibly with an extra copy in there if the compiler is having a very bad day.

    So in the examples you give, I don't think there's much to choose between them. There might be other cases where it matters. But reset does the same template-based capture of the static type of p that the template constructor does, so as far as getting the right deleter is concerned, you're covered.

    The main use of assignment is when you want to copy a previously-existing shared_ptr, to share ownership of the same object. Of course it works fine when assigning from a temporary too, and if you look at the different reset overloads they mirror the different constructors. So I suspect you can achieve the same things either way.

提交回复
热议问题