Accroding到http://en.cppreference.com/w/cpp/memory/unique_ptr/reset,爲什麼unique_ptr過載重置(指針p = pointer())和reset(nullptr_t)?
void reset(pointer ptr = pointer());
template< class U >
void reset(U) = delete;
void reset(std::nullptr_t p);
1)鑑於
current_ptr
,將其通過*this
管理的指針,進行 以下操作,在該順序: 保存當前指針old_ptr = current_ptr
的副本; 用參數current_ptr = ptr
覆蓋當前指針; 如果舊指針不爲空,則刪除先前管理的對象if(old_ptr != nullptr) get_deleter()(old_ptr)
。2)在專業化動態數組,
std::unique_ptr<T[]>
, 該模板構件設置,以防止使用reset()
與 指針衍生(這將導致與 陣列未定義的行爲)。3)在專業化動態數組,
std::unique_ptr<T[]>
,所述 第三過載是必要的,以允許重置爲nullptr
(這將 否則由模板過載被禁止)。相當於reset(pointer())
現在reset(nullptr)
相當於reset(pointer())
,爲什麼後者的存在?
如果我想重置一個數組形式unique_ptr,爲什麼我不能只使用rest(pointer())
?
我真正找到方法'delete'ion更有趣...... – Mehrdad
因爲這將是愚蠢的有'p.reset(nullptr)'是一個編譯錯誤? –
請注意'std :: unique_ptr'只接受'T *'和'T *'作爲其構造函數和'reset'方法的指針類型。值得注意的是,即使它們可以轉換爲指向T的**,它也不接受指向與T不同的類型的指針。換句話說:沒有那個重載'p.reset(nullptr);'不會編譯。這將是非常愚蠢的。 (出於同樣的原因,有'unique_ptr(nullptr_t)'ctor。) –
peppe