Using unique_ptr to control a file descriptor

前端 未结 9 2070
無奈伤痛
無奈伤痛 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:41

    Can you do something simple like the following?

    class unique_fd {
    public:
        unique_fd(int fd) : fd_(fd) {}
        unique_fd(unique_fd&& uf) { fd_ = uf.fd_; uf.fd_ = -1; }
        ~unique_fd() { if (fd_ != -1) close(fd_); }
    
        explicit operator bool() const { return fd_ != -1; }
    
    private:
        int fd_;
    
        unique_fd(const unique_fd&) = delete;
        unique_fd& operator=(const unique_fd&) = delete;
    };
    

    I do not see why you had to use unique_ptr, which is designed to manage pointers.

提交回复
热议问题