Skip to content

Instantly share code, notes, and snippets.

@lw
Last active June 14, 2023 05:04
Show Gist options
  • Save lw/233695418823ab5fa8ae768128cabaa3 to your computer and use it in GitHub Desktop.
Save lw/233695418823ab5fa8ae768128cabaa3 to your computer and use it in GitHub Desktop.
RAII file descriptor wrapper using unique_ptr
#include <iostream>
#include <array>
#include <memory>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
struct FdHandle {
FdHandle() = default;
/* implicit */ FdHandle(std::nullptr_t) { }
explicit FdHandle(int fd) : fd(fd) {}
explicit operator bool() const { return fd != -1; }
friend bool operator==(FdHandle l, FdHandle r) { return l.fd == r.fd; }
friend bool operator!=(FdHandle l, FdHandle r) { return !(l == r); }
int fd{-1};
};
class Fd {
public:
Fd() = default;
Fd(int fd) {
fd_ = decltype(fd_)(FdHandle(fd), Deleter());
}
int getFd() {
return fd_.get().fd;
}
private:
struct Deleter {
using pointer = FdHandle;
void operator()(FdHandle fd) {
::close(fd.fd);
}
};
std::unique_ptr<void, Deleter> fd_;
};
int main() {
Fd f(::open("foo", 0));
::write(f.getFd(), "bar", 3);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment