std::unique_ptr, deleters and the Win32 API

前端 未结 3 1217
情书的邮戳
情书的邮戳 2020-12-01 07:57

In VC2012, I want to create a mutex in a constructor using a unique pointer and a deleter, so that I don\'t need to create a destructor just to call CloseHandle.

I w

3条回答
  •  春和景丽
    2020-12-01 08:40

    Others have pointed out how the whole HANDLE/HANDLE* issue works. Here's a much cleverer way to deal with it, using interesting features of std::unique_pointer.

    struct WndHandleDeleter
    {
      typedef HANDLE pointer;
    
      void operator()(HANDLE h) {::CloseHandle(h);}
    };
    
    typedef std::unique_ptr unique_handle;
    

    This allows unique_handle::get to return HANDLE instead of HANDLE*, without any fancy std::remove_pointer or other such things.

    This works because HANDLE is a pointer and therefore satisfies NullablePointer.

提交回复
热议问题