c++ - 如何使用带有 std::make_unique 的 WinAPI 使用自定义删除器?
问题描述
所以我只是在试验智能指针以及如何HANDLE
用它们管理 Win32 对象,所以我想测试我编写的这个简单代码。
它应该提供一个自定义删除器,std::unique_ptr
以便在智能指针超出范围时使用。
template <typename Function>
class PtrDeleter
{
Function _Closer;
public:
void operator()(void* memBlock) const
{
_Closer(memBlock);
}
};
//The std::make_unique is the one causing the problem...
std::unique_ptr<void*, PtrDeleter<decltype(CloseHandle)>> ptr = std::make_unique<void*>(OpenThread(...));
我为参数使用模板的原因Function
是因为我将使用其他函数CloseHandle
,例如CoTaskMemFree
.
无法从 std::unique_ptr<void *,std::default_delete<_Ty>>' 转换为 'std::unique_ptr<void *,PtrDeleter<BOOL (HANDLE)>>
这就是编译器输出的内容。为什么它仍在尝试使用std::default_delete
with std::make_unique
?
解决方案
make_unique
unique_ptr
使用默认删除器返回。
要提供您的自定义版本,您必须调用ctorunique_ptr(Pointer,Deleter)
的版本:unique_ptr
template <typename Function>
class PtrDeleter {
Function _Closer;
public:
void operator()(void* memBlock) const {
_Closer(memBlock);
}
};
int main() {
PtrDeleter<decltype(&CloseHandle)> deleter;
void* openThread = OpenThread(0,false,0);
std::unique_ptr<void, decltype(deleter)> ptr(openThread,deleter);
}
推荐阅读
- c - 如何在c中将结构变量作为参数传递
- amazon-web-services - 有没有办法在“一个”请求中对 AWSALB cookie 中的“所有”目标组的会话粘性信息进行编码?
- python - 在 Python 中将值从字典写入 CSV
- bots - TypeError:无法读取未定义的不和谐机器人 js 说命令的属性“加入”
- java - 创建自定义命令(即发送原始字节)到 Spring Data Redis?
- python - 如何使以下简单的 Python 函数工作?
- sql - 选择数组中的最后一个公共元素
- apache-spark - 将 Spark 累加器与结构化流结合使用
- excel - 查询按日期和用户对这些行进行分组,在特定事件后开始一个新组
- google-apps-script - TypeError:response.getContentText 不是函数应用脚本