examples

Toy examples in single C files.
git clone git://henryandlizzy.uk/examples
Log | Files | Refs

fd.hpp (814B)


      1 #pragma once
      2 
      3 #include <unistd.h>
      4 #include <utility>
      5 
      6 struct file_descriptor
      7 {
      8 	explicit file_descriptor(int f) noexcept
      9 	:	fd{f}
     10 	{}
     11 
     12 	~file_descriptor() noexcept
     13 	{
     14 		if (*this)
     15 			::close(fd);
     16 	}
     17 
     18 	file_descriptor(file_descriptor const&) = delete;
     19 	file_descriptor& operator =(file_descriptor const&) = delete;
     20 
     21 	file_descriptor(file_descriptor&& old)
     22 	: fd{old.release()}
     23 	{}
     24 
     25 	file_descriptor& operator =(file_descriptor&& old)
     26 	{
     27 		reset(old.release());
     28 		return *this;
     29 	}
     30 
     31 	explicit operator bool() const noexcept
     32 	{
     33 		return fd >= 0;
     34 	}
     35 
     36 	int get() const noexcept {
     37 		return fd;
     38 	};
     39 
     40 	operator int() const noexcept {
     41 		return fd;
     42 	};
     43 
     44 	int release() noexcept
     45 	{
     46 		return std::exchange(fd, -1);
     47 	}
     48 
     49 	void reset(int f = -1) noexcept
     50 	{
     51 		file_descriptor{std::exchange(fd, f)};
     52 	}
     53 
     54 private:
     55 	int fd = -1;
     56 };
     57