gpt4 book ai didi

c++ - 为什么 unique_ptr 会重载 reset(pointer p = pointer()) 和 reset(nullptr_t)?

转载 作者:太空狗 更新时间:2023-10-29 19:58:13 30 4
gpt4 key购买 nike

根据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 pointer old_ptr = current_ptr; Overwrites the current pointer with the argument current_ptr = ptr; If the old pointer was non-empty, deletes the previously managed object if(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 using reset() 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 to nullptr (which would otherwise be prohibited by the template overload). Equivalent to reset(pointer())

现在reset(nullptr)相当于reset(pointer()) ,为什么后者存在?

如果我想重置一个数组形式的 unique_ptr,为什么我不能只使用 rest(pointer())

最佳答案

template< class U > 
void reset( U ) = delete;

将被选择用于带有 nullptr 参数的调用,如果不是用于

void reset( std::nullptr_t p );

这就是它存在的原因,允许使用 nullptr 进行调用。


示例(使用定义的 FIX 编译以抑制编译错误):

#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.
}

关于c++ - 为什么 unique_ptr 会重载 reset(pointer p = pointer()) 和 reset(nullptr_t)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24359194/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com