How to use C++ standard smart pointers with Windows HANDLEs?

后端 未结 10 1124
Happy的楠姐
Happy的楠姐 2020-12-17 19:04

I was wondering if there is a way to use unique_ptr with Windows HANDLEs?

I was thinking to replace the std::default_delete with s

10条回答
  •  被撕碎了的回忆
    2020-12-17 19:47

    Here is a handy little "custom_ptr" I use for dealing with a HANDLE. C++17 is required in order for this to compile. This idea was lifted from another SO post, I only added the std::remove_pointer_t so that I wouldn't have to pass void as the custom_ptr type parameter.

    Definition

    #include 
    #include 
    
    template
    using deleter_from_fn = std::integral_constant;
    
    template
    using custom_ptr = std::unique_ptr, deleter_from_fn>;
    

    Use

    custom_ptr phandle{
        CreateFileMapping( INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, 1024, L"FileName" ) };
    

提交回复
热议问题