Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Agreed. Author is trying to mix paradigms. Simplest approach if they want local handling and non-propagation of errors is to just have the file holder not check for open success, and check that manually after construction. Then you get guaranteed closure of file no matter how the function is exited.

  class File_handle {
      FILE *p;
  public:
      File_handle(const char *pp, const char *r)  { p = fopen(pp, r); }
      ~File_handle() { if ( p ) fclose(p); }
      FILE* file() const { return p; }
  };
  
  
  void f(string s)
  {
      File_handle fh { s, "r"};
      if ( fh.file() == NULL ) {
          fprintf(stderr, "failed to open file '%s', error=%d\n", p, errno);
          return;
      }
      // use fh
  }


Goes against "Resource acquisition is initialization" though to have objects which exist but can't be used. (I think that's the relevant pattern?)

However, where the language and it's objects and memory ends and the external world begins, like files and sockets... that's always tricky.


this may lose the value of errno, right?


Yes, it would. It would be trivial to add errno as an instance variable for File_Handle class though.


Kind of the opposite. You lose the fragility and imprecision of and non-extensibility of errno. Good riddance!




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: