为什么超负荷的unique_ptr复位(指针p =指针())和reset(nullptr_t)? [英] Why does unique_ptr overload reset(pointer p = pointer()) and reset(nullptr_t)?
问题描述
Accroding到 HTTP://en.cp$p$ pference.com/w/cpp/memory/unique_ptr/reset ,
无效复位(PTR指针指针=());模板<类U>
无效复位(U)=删除;无效复位(的std :: nullptr_t P);
1)给定
current_ptr
,这是由管理指针*本
,执行
以下操作,顺序如下:
保存当前指针的拷贝old_ptr = current_ptr
;
覆盖当前指针与参数current_ptr = PTR
;
如果旧的指针是否非空,删除previously管理对象如果(old_ptr!= nullptr)get_deleter()(old_ptr)
。
2)在专业化的动态数组,
的std ::的unique_ptr< T []>
,
这个模板部件设在prevent使用复位()
带
指针衍生(这将导致与未定义行为
阵列)。
3)在专业化的动态数组,
的std ::的unique_ptr< T []>
中,
第三个重载是必要的,让重置为nullptr
(这将
否则由模板超载被禁止)。相当于
复位(指针())
块引用>现在
复位(nullptr)
等同于复位(指针())
,为什么后者存在?如果我想重置阵列形式的unique_ptr,为什么我不能只是使用
休息(指针())
?解决方案的
模板<类U>
无效复位(U)=删除;将选择与
nullptr
参数调用,如果不是无效复位(的std :: nullptr_t P);
这就是为什么它的存在,让与呼叫
nullptr
。示例(编译
FIX
定义燮preSS编译错误):的#include< cstddef> //的std :: nullptr_t的struct
{
无效复位(字符*){} 模板<类类型>
无效复位(类型)=删除; #如果FIX
无效复位(的std :: nullptr_t){}
#万一
};汽车的main() - GT; INT
{
。S()复位(nullptr);没有定义FIX时//失败。
}Accroding to http://en.cppreference.com/w/cpp/memory/unique_ptr/reset,
void reset( pointer ptr = pointer() ); template< class U > void reset( U ) = delete; void reset( std::nullptr_t p );
1) Given
current_ptr
, the pointer that was managed by*this
, performs the following actions, in this order: Saves a copy of the current pointerold_ptr = current_ptr
; Overwrites the current pointer with the argumentcurrent_ptr = ptr
; If the old pointer was non-empty, deletes the previously managed objectif(old_ptr != nullptr) get_deleter()(old_ptr)
.2) In the specialization for dynamic arrays,
std::unique_ptr<T[]>
, this template member is provided to prevent usingreset()
with a pointer to derived (which would result in undefined behavior with arrays).3) In the specialization for dynamic arrays,
std::unique_ptr<T[]>
, the third overload is necessary to allow reset tonullptr
(which would otherwise be prohibited by the template overload). Equivalent toreset(pointer())
Now that
reset(nullptr)
is equivalent toreset(pointer())
, why does the latter exist?If I want to reset an array form unique_ptr, why can I not just use
rest(pointer())
?解决方案The
template< class U > void reset( U ) = delete;
would be chosen for a call with
nullptr
argument, if not forvoid reset( std::nullptr_t p );
That's why it exists, to allow the call with
nullptr
.
Example (compile with
FIX
defined to suppress the compilation error):#include <cstddef> // std::nullptr_t struct S { void reset( char* ) {} template< class Type > void reset( Type ) = delete; #if FIX void reset( std::nullptr_t ) {} #endif }; auto main() -> int { S().reset( nullptr ); // Fails when FIX is not defined. }
这篇关于为什么超负荷的unique_ptr复位(指针p =指针())和reset(nullptr_t)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!