fork(1) download
  1. #include <iostream>
  2. #include <sys/stat.h>
  3. #include <fcntl.h>
  4. #include <thread>
  5. #include <memory>
  6. #include <unistd.h>
  7. #include <atomic>
  8.  
  9. class FD
  10. {
  11. private:
  12. int fd;
  13. int* count;
  14.  
  15. public:
  16. FD(const char* FilePath, int flags) : fd(open(FilePath, flags)), count(new int(1)) {}
  17. FD(const FD& other) : fd(other.fd), count(other.count) {*count += 1;}
  18. FD(FD&& other) : fd(other.fd), count(other.count) { other.count = nullptr; other.fd = -1; }
  19.  
  20. ~FD()
  21. {
  22. *count -= 1;
  23. if (*count == 0)
  24. {
  25. std::cout<<"Destroyed\n";
  26. delete count;
  27. count = NULL;
  28.  
  29. if (is_open())
  30. close(fd);
  31. }
  32. }
  33.  
  34. bool is_open() {return fd != -1;}
  35. FD* operator &() {return nullptr;}
  36. operator int() {return fd;}
  37.  
  38. FD& operator = (FD other)
  39. {
  40. fd = other.fd;
  41. count = other.count;
  42. *count += 1;
  43. return *this;
  44. }
  45.  
  46. FD& operator = (FD&& other)
  47. {
  48. fd = other.fd;
  49. count = other.count;
  50. other.fd = -1;
  51. other.count = NULL;
  52. return *this;
  53. }
  54. };
  55.  
  56. int main()
  57. {
  58. FD fd = FD("Unicode.cpp", O_RDONLY);
  59. FD copy = fd;
  60. FD cpy = FD(copy);
  61.  
  62. return 0;
  63. }
  64.  
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
Destroyed