[英]Smart pointer deleter and “using” keyword with a name “pointer”
有时候我看到这样的代码:
void* Create()
{
int* t{new int{10}};
return t;
}
class Deleter
{
//uncomment in order to compile
//using pointer = void*;
public:
void operator()(void* t)
{
delete t;
}
};
unique_ptr<int, Deleter> ptr{Create()};
它没有编译。 使用VS2013,它说:
错误:C2440:'初始化':无法从'initializer-list'转换为'std :: unique_ptr'没有构造函数可以采用源类型,或者构造函数重载解析是模糊的
但如果我using pointer = void*;
取消注释行using pointer = void*;
有用! 此外,如果我将别名更改为与pointer
不同的名称,我会得到相同的错误。 所以似乎using
具有确切名称pointer
的using
指令是至关重要的。 但为什么? 我找不到任何解释。
您的unique_ptr
用T=int
声明。 但是, std::unique_ptr
构造函数不是T*
,而是pointer
参数。
此pointer
类型定义为
std::remove_reference<Deleter>::type::pointer if that type exists, otherwise T*
当你不提供Deleter::pointer
它最终会变成int*
,当然也不能从void*
(来自Create
)初始化。
[C++11: 20.7.1.2/3]
如果类型remove_reference<D>::type::pointer
存在,那么unique_ptr<T, D>::pointer
应该是remove_reference<D>::type::pointer
的同义词remove_reference<D>::type::pointer
。 否则unique_ptr<T, D>::pointer
应该是T*
的同义词。unique_ptr<T, D>::pointer
应满足NullablePointer (17.6.3.3)的要求。
这是必需的,因为你没有operator()(int*)
- 你正在“黑客”,允许使用operator()(void*)
代替删除器假装它是void*
的删除器。
你的删除器整体是否仍然严格有效,即使它编译,我也不想说。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.