3 ms·
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
by gblargg 11mo ago
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
}
- mikhael 11mo agothis may lose the value of errno, right?
- actionfromafar 11mo agoGoes 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.