The Resource Loan pattern
The Loan pattern, as the name suggest, loans a resource to a function In the example given below, a file handle is loaned to consumers of the class. It performs following steps:
- It creates a resource that you can use (a file handle )
- It loans the resource (file handle ) to functions (lambdas) that will use it
- This function is passed by the caller and executed by the resource holder
- The resource (file handle ) is closed or destroyed by the resource holder
The following code implements the Resource Loan pattern for resource management. The pattern helps to avoid resource leakage when writing code:
//----------- ResourceLoan.cpp #include <rxcpp/rx.hpp> using namespace std; ////////////////////////// // implementation of Resource Loan Pattern. The Implementation opens a file // and does not pass the file handle to user defined Lambda. The Ownership remains with // the class class ResourceLoan { FILE *file; // This is the resource which is being...