diff options
| author | Joel Klinghed <the_jk@spawned.biz> | 2025-02-20 22:54:56 +0100 |
|---|---|---|
| committer | Joel Klinghed <the_jk@spawned.biz> | 2025-02-20 22:54:56 +0100 |
| commit | b4d6df902253637f24647d3db2bc3781d69eec1c (patch) | |
| tree | d8bf9ac04a270fabdfee1c15628c702471ef8bf5 /src/unique_fd.hh | |
| parent | 441cafc7124f633e5abc684e85a11ce3c991f6ae (diff) | |
Diffstat (limited to 'src/unique_fd.hh')
| -rw-r--r-- | src/unique_fd.hh | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/src/unique_fd.hh b/src/unique_fd.hh new file mode 100644 index 0000000..dc60b3f --- /dev/null +++ b/src/unique_fd.hh @@ -0,0 +1,48 @@ +#ifndef UNIQUE_FD_HH +#define UNIQUE_FD_HH + +#include <cstddef> + +class unique_fd { +public: + constexpr unique_fd() noexcept + : fd_(-1) {} + constexpr unique_fd(std::nullptr_t) noexcept + : fd_(-1) {} + explicit unique_fd(int fd) noexcept + : fd_(fd) {} + unique_fd(unique_fd&& fd) noexcept + : fd_(fd.release()) {} + + ~unique_fd() { reset(); } + + unique_fd& operator=(unique_fd&& fd) noexcept { + reset(fd.release()); + return *this; + } + unique_fd& operator=(std::nullptr_t) noexcept { + reset(); + return *this; + } + + int get() const noexcept { return fd_; } + int operator*() const { return get(); } + + explicit operator bool() const noexcept { return fd_ >= 0; } + + int release() noexcept { + int ret = fd_; + fd_ = -1; + return ret; + } + + void reset(int fd = -1); + +private: + unique_fd(unique_fd const&) = delete; + unique_fd& operator=(unique_fd const&) = delete; + + int fd_; +}; + +#endif // UNIQUE_FD_HH |
