use*_*241 8 c++ gcc unique-ptr c++11 gcc6
从C++中的GCC 6开始,unique_ptr<T[]>::reset方法的声明/定义(不是仅接受的方法nullptr_t)如下所示:
template <typename _Up,
typename = _Require<
__or_<is_same<_Up, pointer>,
__and_<is_same<pointer, element_type*>,
is_pointer<_Up>,
is_convertible<
typename remove_pointer<_Up>::type(*)[],
element_type(*)[]
>
>
>
>>
void
reset(_Up __p) noexcept
{
using std::swap;
swap(std::get<0>(_M_t), __p);
if (__p != nullptr)
get_deleter()(__p);
}
Run Code Online (Sandbox Code Playgroud)
在某些时候改变了这一点以实现N4089.根据该文件:
此函数的行为与主模板的重置成员相同,除非它不参与重载解析
-
U是相同的类型pointer,或者-
pointer是类型element_type*,U是指针类型V*,V(*)[]可以转换为element_type(*)[].
让我们考虑以下示例:
std::unique_ptr<const char []> ptr1;
std::unique_ptr<char []> ptr2(new char[5]);
ptr1 = std::move(ptr2);
Run Code Online (Sandbox Code Playgroud)
由于版本6 GCC产生错误,抱怨它无法std::swap使用const char*&和调用char*&.
reset方法发生在char[]可转换为的重载决策中const char[],但自然会std::swap等待两个相同类型的引用.
这被认为是正确的行为吗?如果是这样,为什么呢?如果我可以隐式转换char[]为const char[],为什么同样不可能用unique_ptr?