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

后端 未结 10 1114
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:51

    You can typedef your unique_ptr with a custom deleter

    struct handle_deleter
    {
        void operator()(void* handle)
        {
            if(handle != nullptr)
                CloseHandle(handle);
        }
    };
    
    typedef std::unique_ptr UniqueHandle_t;
    UniqueHandle_t ptr(CreateFile(...));
    

提交回复
热议问题