| A class Resource and its application in the function use_resource - principles only. | Lecture 3 - slide 11 : 36 Program 1 |
// Incomplete program that illustrates the RAII idea. Does not compile.
class Resource{
private:
resource_type r;
resource_id_t rti;
public:
Resource(resource_id_t id): r(allocate_resource(id)), rti(id){
}
~Resource() {
release_resource(rti);
}
private:
resource_type allocate_resource(resource_id_t id){
return ...;
}
void release_resource(resource_id_t id){
...
}
};
void use_resource(resource_id_t r){
Resource res(r); // The constructor allocates the resource
// ...
// When the functions ends, or if an exception occurs before that,
// the Resource destructor will be activated hereby relinquising it.
};
int main(){
use_resource(actual_resource_id);
}