std::unique_ptr::reset 重载问题

问题描述

来自https://en.cppreference.com/w/cpp/memory/unique_ptr/reset 主模板的成员,unique_ptr

void reset( pointer ptr = pointer() ) noexcept;     (1)     

        
template< class U >
void reset( U ) noexcept;       (2)     
void reset( std::nullptr_t p = nullptr ) noexcept;      (3)     

对我来说,对于 (1),如果没有给出参数,则将调用指针类型的认构造函数。但是它应该表现为一个nullptr,这样unique_ptr里面的指针就会被删除,并且会被设置为null,这是怎么回事?

对(2)的解释是

2) Behaves the same as the reset member of the primary template,except that it will only participate in overload resolution if either:    
    U is the same type as pointer,or
    pointer is the same type as element_type* and U is a pointer type V* such that V(*)[] is convertible to element_type(*)[].

我真的无法理解,有人可以解释/改写吗?

解决方法

对我来说,对于 (1),如果没有给出参数,则将调用指针类型的默认构造函数。但是它应该表现为一个nullptr,这样unique_ptr里面的指针就会被删除,并且会被设置为null,这是怎么回事?

指针类型的默认构造函数”并不是真正的东西 - 但是,是的,默认参数是一个初始化为零的 T* ,它与您的效果相同之后。 pointer()(其中 pointertypedefT*)将被初始化为 nullptr

using pointer = foo*;    // example pointer typedef
pointer ptr = pointer(); // initialized to nullptr by default

这相当于 nullptr,任何持有的资源都将被释放。

重载 (2) 和 (3) 用于数组特化,其中 U = T[].