Back to slide -- Keyboard shortcut: 'u'        next -- Keyboard shortcut: 'n'          raii/raii-pattern-0.cc - A class Resource and its application in the function use_resource - principles only.Lecture 4 - slide 13 : 40
Program 1

// Incomplete program that illustrates the RAII idea. Does not compile.

class Resource{
private:
  resource_type r;          // Encapsulaton of resource in a class
  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 on the stack

  // ...

  // 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);

}