std::shared_ptr: reset() vs. assignment

后端 未结 4 1376
小鲜肉
小鲜肉 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:28

    It's possible for reset to avoid a dynamic memory allocation in certain cases. Consider the code

    std::shared_ptr p{new int{}};  // 1
    p.reset(new int{});                 // 2
    

    On line 1 there are 2 dynamic memory allocations happening, one for the int object and a second one for the shared_ptr's control block that'll keep track of the number of strong/weak references to the managed object.

    On line 2 there is again a dynamic memory allocation for a new int object. Within the body of reset the shared_ptr will determine that there are no other strong references to the previously managed int, so it must delete it. Since there aren't any weak references either, it could also deallocate the control block, but in this case it would be prudent for the implementation to reuse the same control block because it would otherwise have to allocate a new one anyway.

    The above behavior would not be possible if you always had to use assignment.

    std::shared_ptr p{new int{}};    // 1
    p = std::shared_ptr{new int{}};  // 2
    

    In this case, the second call to the shared_ptr constructor on line 2 has already allocated a control block, so p will have to deallocate its own existing control block.

提交回复
热议问题