What
Represent a resource by a local object, so that the local object’s destructor will release the resource it owned.
Rust do this automatically, using the Drop
trait.
Why
Programmer cannot forget to release the resource, and thus avoid resource leak
How
class File_handle {
FILE* p;
public:
File_handle(const char* n, const char* a)
{ p = fopen(n,a); if (p) throw Open_error(errno); }
File_handle(FILE* pp)
{ p = pp; if (p) throw Open_error(errno); }
~File_handle() { fclose(p); }
operator FILE*() { return p; }
// ...
};
void f(const char* fn)
{
File_handle f(fn,"rw"); // open fn for reading and writing
// use file through f
}