[英]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;
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.