c++ - 对 Windows HANDLE 使用 std::unique_ptr

标签 c++ visual-c++ c++11 visual-studio-2012 unique-ptr

我正在尝试使用 std::unique_ptrs 以异常安全的方式管理 Windows HANDLE。

首先我尝试过:

struct HandleDeleter
{
    void operator()( HANDLE handle )
    {
        if( handle )
        {
            FindVolumeClose( handle )
        }
    }
}
typedef std::unique_ptr< HANDLE, HandleDeleter > unique_vol_handle_t;

稍后在我尝试使用它的代码中:

unique_vol_handle_t volH(FindFirstVolumeW(buffer, MAX_GUID_PATH));

我从 Visual Studio 2012RC 收到以下错误:

1>          error C2664: 'std::unique_ptr<_Ty,_Dx>::unique_ptr(std::nullptr_t) throw()' : cannot convert parameter 1 from 'HANDLE' to 'std::nullptr_t'
1>          with
1>          [
1>              _Ty=HANDLE,
1>              _Dx=VolumeHandleDeleter
1>          ]
1>          nullptr can only be converted to pointer or handle types

引用上面的 volH 声明行。

搜索了一段时间,找到了a blog article基本上说,添加:

typedef HANDLE 指针;

到结构声明的顶部,一切都会好起来的。

我不相信,但我试过了,它确实解决了错误。我很困惑如何定义一个类型(甚至不引用它)会产生如此大的不同。

两个问题:

1) 你能解释一下原来的错误吗?我不明白为什么编译器指的是 std::nullptr_t/nullptr

2) typedef 是如何解决这个问题的(或者至少看起来是这样)?有没有更“诡异的远距离 Action ”解决方案?

最佳答案

unique_ptr 的实现检查是否存在 ::pointer在删除器上键入。如果删除器有 ::pointer类型,则此类型用作 pointer unique_ptr 上的 typedef .否则使用指向第一个模板参数的指针。

根据cppreference.com , unique_ptr::pointer类型定义为

std::remove_reference<D>::type::pointer if that type exists, otherwise T*

关于c++ - 对 Windows HANDLE 使用 std::unique_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12184779/

相关文章:

c++ - 具有函数指针的类,可以在不同实例中调用多种函数

c++ - Objective-C++的缺点?

c++ - 按值或引用 const 传递 std::chrono::duration?

c++ - std::thread 类方法错误

c++ - atoi() 与其他语言

c++ - 获取 LNK1104 : cannot open file "libssl.obj"

c++ - 棘手的 C 问题。动态函数调用

数组和字符串破解编码面试第 6 版解决方案 1.1

c++ - std::unique_ptr 用法

c++ - 由于 C++ 中的段错误而导致应用程序崩溃的方法