Using unique_ptr to control a file descriptor

前端 未结 9 2086
無奈伤痛
無奈伤痛 2020-12-10 05:29

In theory, I should be able to use a custom pointer type and deleter in order to have unique_ptr manage an object that is not a pointer. I tried the following c

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 05:56

    The type exposed by the Deleter::pointer must satisfy the NullablePointer requirements. Chief among them, this expression must be legal: Deleter::pointer p = nullptr;. Of course, nullptr is pretty much defined by the fact that it cannot be implicitly converted to a number, thus this doesn't work.

    You'll have to use a type which can be implicitly constructed with std::nullptr_t. Something like this:

    struct file_desc
    {
      file_desc(int fd) : _desc(fd) {}
      file_desc(std::nullptr_t) : _desc(-1) {}
    
      operator int() {return _desc;}
    
      bool operator ==(const file_desc &other) const {return _desc == other._desc;}
      bool operator !=(const file_desc &other) const {return _desc != other._desc;}
      bool operator ==(std::nullptr_t) const {return _desc == -1;}
      bool operator !=(std::nullptr_t) const {return _desc != -1;}
    
      int _desc;
    };
    

    You can use that as the Deleter::pointer type.

提交回复
热议问题