如何解决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()
(其中 pointer
是 typedef
的 T*
)将被初始化为 nullptr
。
using pointer = foo*; // example pointer typedef
pointer ptr = pointer(); // initialized to nullptr by default
这相当于 nullptr
,任何持有的资源都将被释放。
重载 (2) 和 (3) 用于数组特化,其中 U = T[]
.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。