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

后端 未结 10 1090
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<void, handle_deleter> UniqueHandle_t;
    UniqueHandle_t ptr(CreateFile(...));
    
    0 讨论(0)
  • 2020-12-17 20:00

    yet another solution

    std::unique_ptr< void, void(*)( HANDLE ) > uniqueHandle( file, []( HANDLE h ) { ::CloseHandle( h ); } );
    
    0 讨论(0)
  • 2020-12-17 20:01

    I don't recommend using smart pointers with handles.

    I recommend you to take a look at A Proposal to Add additional RAII Wrappers to the Standard Library and at the drawbacks of using smart pointers with handles.

    Personally, I'm making use of the reference implementation of that proposal instead of using std::unique_ptr for these situations.

    0 讨论(0)
  • 2020-12-17 20:02

    Create a specific smart pointer class, won't take long. Don't abuse library classes. Handle semantics is quite different from that of a C++ pointer; for one thing, dereferencing a HANDLE makes no sense.

    One more reason to use a custom smart handle class - NULL does not always mean an empty handle. Sometimes it's INVALID_HANDLE_VALUE, which is not the same (actually -1).

    0 讨论(0)
提交回复
热议问题