【问题标题】:std::unique_ptr::reset overloads questionsstd::unique_ptr::reset 重载问题
【发布时间】:2021-05-30 13:57:45
【问题描述】:

来自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(*)[].

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

【问题讨论】:

    标签: c++ c++11 smart-pointers unique-ptr


    【解决方案1】:

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

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

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

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

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

    【讨论】:

    • 我不太明白 pointer() 如何/为什么是 nullptr?
    • @Johy 这是初始化指针时的默认值。也许this 的例子更清楚地说明了这一点。
    • 谢谢。我现在看到它是如何工作的,但仍然不明白为什么。关于使用开始阅读en.cppreference.com/w/cpp/language/type_alias,但是如何调用pointer()的这种用法呢?因为它不是默认构造函数,所以它是别的东西?
    • 啊,嗯,它是类型的构造。就像int initialized = int(); 一样,它会生成一个int,其值为0
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-14
    • 2017-02-24
    • 2012-12-01
    • 1970-01-01
    • 2018-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多