Making a HANDLE RAII-compliant using shared_ptr with a custom deleter

前端 未结 4 947
广开言路
广开言路 2021-01-02 04:35

I\'ve recently posted a general question about RAII at SO. However, I still have some implementation issues with my HANDLE example.

A HANDLE is typedeff

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-02 05:27

    Example 1 is OK

    Example 2 is wrong. By blindly casting to PHANDLE, the shared_ptr logic is bypassed. It should be something like this instead:

    HANDLE h;
    OpenProcessToken(...., &h);
    shared_ptr safe_h(h, &::CloseHandle);
    

    or, to assign to a pre-exising shared_ptr:

    shared_ptr safe_h = ....
    {
      HANDLE h;
      OpenProcessToken(...., &h);
      safe_h.reset(h, &::CloseHandle);
    }//For extra safety, limit visibility of the naked handle
    

    or, create your own, safe, version of OpenProcessToken that returns a shared handle instead of taking a PHANDLE:

    // Using SharedHandle defined at the end of this post
    SharedHandle OpenProcess(....)
    {
        HANDLE h = INVALID_HANDLE_VALUE;
        ::OpenProcessToken(...., &h);
        return SharedHandle(h);
    }
    

    Example 3: No need to take these detours. This should be ok:

    Process32First(h.get(), ...);
    

    Example 4: Again, no detour:

    if (h.get() == INVALID_HANDLE){...}
    

    To make things nicer, you could typedef something like:

    typedef shared_ptr SharedHandle;
    

    or better yet, if all handles are to be closed with CloseHandle(), create a SharedHandle class wrapping a shared_ptr and automatically providing the right deleter:

    // Warning: Not tested. For illustration purposes only
    class SharedHandle
    {
    public:
      explicit SharedHandle(HANDLE h) : m_Handle(h, &::CloseHandle){};
      HANDLE get()const{return m_Handle.get();}
    
      //Expose other shared_ptr-like methods as needed
      //...
    
    private:
      shared_ptr m_Handle;
    };
    

提交回复
热议问题