PPT Slide
int main() {struct local_file { local_file() : f(std::fopen(__FILE__, "r")) {} ~local_file() { if (f) std::fclose(f); }
operator std::FILE* () const { return f; }
if (file) { std::fread(buffer, sizeof buffer, 1, file); // Processing that may throw an exception}
struct local_file { local_file() : f(std::fopen(__FILE__, "r")) {} ~local_file() { if (f) std::fclose(f); }
operator std::FILE* () const { return f; }
Notes:
A local class can be used to release a resource used in a function. By releasing the resource in the destructor we can guarantee releasing the resource in the presence of exceptions.
In most cases it is better to produce a complete wrapper class rather than the rather trusting implementation shown here.