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

前端 未结 2 871
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  旧时难觅i
    2020-12-04 14:30

    Shared pointers of different types can share the ownership of the same object. See overload (8) of std::shared_ptr::shared_ptr. Unique pointers don't need such a mechanism, as they don't share.

    template< class Y > 
    shared_ptr( const shared_ptr& r, element_type* ptr ) noexcept;
    

    If you didn't type-erase the deleter, you wouldn't be able to use such a shared_ptr as a shared_ptr, which would make it basically useless.

    Why would you want such an overload?

    Consider

    struct Member {};
    struct Container { Member member };
    

    If you want to keep the Container alive, while you use the Member, you can do

    std::shared_ptr pContainer = /* something */
    std::shared_ptr pMember(pContainer, &pContainer->member);
    

    and only have to hold onto pMember (perhaps put it into a std::vector>)

    Or alternatively, using overload (9)

    template< class Y > 
    shared_ptr( const shared_ptr& r ) noexcept; 
      // Only exists if Y* is implicitly convertible to T*
    

    You can have polymorphic sharing

    struct Base {};
    struct Derived : Base {};
    
    void operate_on_base(std::shared_ptr);
    
    std::shared_ptr pDerived = /* something*/
    operate_on_base(pDerived);
    

提交回复
热议问题