Why does unique_ptr take two template parameters when shared_ptr only takes one?

前端 未结 2 832
隐瞒了意图╮
隐瞒了意图╮ 2020-12-04 14:24

Both unique_ptr and shared_ptr accept a custom destructor to call on the object they own. But in the case of unique_ptr, the destructor is passed as a template

2条回答
  •  自闭症患者
    2020-12-04 14:40

    If you provide the deleter as template argument (as in unique_ptr) it is part of the type and you don't need to store anything additional in the objects of this type. If deleter is passed as constructor's argument (as in shared_ptr) you need to store it in the object. This is the cost of additional flexibility, since you can use different deleters for the objects of the same type.

    I guess this is the reason: unique_ptr is supposed to be very lightweight object with zero overhead. Storing deleters with each unique_ptr could double their size. Because of that people would use good old raw pointers instead, which would be wrong.

    On the other hand, shared_ptr is not that lightweight, since it needs to store reference count, so storing a custom deleter too looks like good trade off.

提交回复
热议问题