簡體   English   中英

為什么我不能刪除unique_ptr <char[]> 用reset()?

[英]Why cannot I delete unique_ptr<char[]> with reset()?

當我有一個指向單個對象的唯一指針時,我可以使用reset()刪除它:

std::unique_ptr<char> variable(new char);
variable.reset();

但是,這對包含數組的std::unique_ptr不起作用。 為什么? 刪除這樣的指針的正確方法是什么?

我正在使用Embarcadero C ++ Builder 10.1。 相關標准是C ++ 11。

我的觀察

當我有一個包含數組的唯一指針時,無法編譯:

std::unique_ptr<char[]> variable(new char[10]);
variable.reset();

錯誤消息no matching function to call for 'reset'

這也失敗了:

std::unique_ptr<char[]> variable(new char[10]);
variable.reset(nullptr);

錯誤消息cannot initialize a variable of type 'pointer' (aka 'char *') with an lvalue of type '<bound member function type>'assigning to '<bound member function type>' from incompatible type '_Null_ptr_type' (aka 'nullptr_t')

這編譯:

std::unique_ptr<char[]> variable(new char[10]);
variable = nullptr;

來自<memory>的相關代碼

template<class _Uty>
using _Enable_ctor_reset = enable_if_t<
    is_same<_Uty, pointer>::value
    || (is_same<pointer, element_type *>::value
    && is_pointer<_Uty>::value
    && is_convertible<
        remove_pointer_t<_Uty>(*)[],
        element_type(*)[]
    >::value)>;

_Myt& operator=(_Null_ptr_type) _NOEXCEPT
    {   // assign a null pointer
    reset(pointer());
    return (*this);
    }

_NOINLINE void reset(_Null_ptr_type _Ptr) _NOEXCEPT
    {   // establish new null pointer
    pointer _Old = this->_Myptr;
    this->_Myptr = _Ptr;
    if (_Old != pointer())
        this->get_deleter()(_Old);
    }

template<class _Uty,
    class = _Enable_ctor_reset<_Uty> >
void reset(_Uty _Ptr) _NOEXCEPT
    {   // establish new pointer
    pointer _Old = get();
    this->_Myptr() = _Ptr;
    if (_Old != pointer())
        this->get_deleter()(_Old);
    }

似乎這是標准庫中的一個錯誤,因為相同的代碼與其他編譯器編譯,正如deW1sanjay在評論中指出的那樣。

C ++ 11標准的第20.7.1.3節( “具有運行時長度的數組對象的unique_ptr” )列出了帶有以下簽名的reset()

void reset(指針p =指針())noexcept;

第一個示例無法編譯,因為標准庫實現中缺少默認參數。 第二個例子本質上調用reset(pointer()) ,它無法編譯。 可能這個編譯錯誤是沒有添加默認參數的原因。

我向Embarcadero做了一個錯誤報告:

RSP-16165在包含unique_ptr的數組對象上調用reset()時編譯錯誤

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM