nik*_*ack 8 c++ smart-pointers
有时候我看到这样的代码:
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()};
Run Code Online (Sandbox Code Playgroud)
它没有编译.使用VS2013,它说:
错误:C2440:'初始化':无法从'initializer-list'转换为'std :: unique_ptr'没有构造函数可以采用源类型,或构造函数重载解析不明确
但如果我取消注释using pointer = void*;它的工作原理!此外,如果我将别名更改为不同于pointer我得到相同错误的名称.所以似乎拥有一个using具有确切名称的指令pointer是至关重要的.但为什么?我找不到任何解释.
小智 7
你unique_ptr声明了T=int.但是,构造函数std::unique_ptr不是T*,而是pointer参数.
此pointer类型定义为
std::remove_reference<Deleter>::type::pointer if that type exists, otherwise T*
Run Code Online (Sandbox Code Playgroud)
当你不提供Deleter::pointer它时int*,它当然不能从void*(从Create)初始化.