2 // UtilFileDescriptor.hpp
5 // Created by James McIlree on 4/16/13.
6 // Copyright (c) 2013 Apple. All rights reserved.
9 #ifndef CPPUtil_UtilFileDescriptor_hpp
10 #define CPPUtil_UtilFileDescriptor_hpp
12 class FileDescriptor {
16 // FD's aren't reference counted, we allow move semantics but
17 // not copy semantics. Disable the copy constructor and copy
19 FileDescriptor(const FileDescriptor& that) = delete;
20 FileDescriptor& operator=(const FileDescriptor& other) = delete;
24 FileDescriptor() : _fd(-1) {}
25 FileDescriptor(int fd) : _fd(fd) {}
27 template <typename... Args>
28 FileDescriptor(Args&& ... args) :
29 _fd(open(static_cast<Args &&>(args)...))
33 FileDescriptor (FileDescriptor&& rhs) noexcept :
39 ~FileDescriptor() { close(); }
41 FileDescriptor& operator=(int fd) { close(); _fd = fd; return *this; }
42 FileDescriptor& operator=(FileDescriptor&& rhs) { std::swap(_fd, rhs._fd); return *this; }
44 bool is_open() const { return _fd > -1 ? true : false; }
45 void close() { if (is_open()) { ::close(_fd); _fd = -1; } }
47 explicit operator bool() const { return is_open(); }
48 operator int() const { return _fd; }