首页 > 解决方案 > 如何使用带有 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_deletewith std::make_unique

标签: c++winapistlsmart-pointers

解决方案


make_uniqueunique_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);
}

演示


推荐阅读