summaryrefslogtreecommitdiff
path: root/src/unique_fd.hh
blob: 189d51362a924f0bbce21afa23c346756749be94 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#ifndef UNIQUE_FD_HH
#define UNIQUE_FD_HH

class unique_fd {
 public:
  constexpr unique_fd()
      : fd_(-1) {}
  explicit constexpr unique_fd(int fd)
      : fd_(fd) {}
  unique_fd(unique_fd& fd) = delete;
  unique_fd& operator=(unique_fd& fd) = delete;
  unique_fd(unique_fd&& fd)
      : fd_(fd.release()) {}
  unique_fd& operator=(unique_fd&& fd) {
    reset(fd.release());
    return *this;
  }
  ~unique_fd() {
    reset();
  }

  bool operator==(unique_fd const& fd) const {
    return get() == fd.get();
  }
  bool operator!=(unique_fd const& fd) const {
    return get() != fd.get();
  }

  int get() const { return fd_; }
  explicit operator bool() const { return fd_ != -1; }
  int operator*() const { return fd_; }

  int release() {
    int ret = fd_;
    fd_ = -1;
    return ret;
  }

  void reset(int fd = -1);

 private:
  int fd_;
};

#endif  // UNIQUE_FD_HH