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

// Complete program that illustrates the RAII idea. Does compile.
// This version just reveals the resource allocation and deallocation on standard output. 
// Just a detailed setup that illustrates that the resource always is released - 
// in both normal return situations, and in exceptional situations.

#include <iostream>
#include <string>
#include <cstring>

using namespace std;

typedef string resource_id_t;
typedef int resource_type;

class Problem{};

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){
    cout << "Allocate resource: " << id << endl;
    return 1;
  }

  void release_resource(resource_id_t id){
    r = 0;
    cout << flush << "Release resource: " << id << flush << endl;
  }
};

void use_resource(resource_id_t r, bool problem_condition){
  Resource res(r);         // The constructor allocates the resource

  cout << "Use Resource" << endl;

  if (problem_condition){
    cout << "An exception is thrown" << endl;
    throw Problem();
  }

  // When the functions ends, or if an exception occurs before that,
  // the Resource destructor will be activated hereby relinquising it.
};

int main(int argc, char *argv[]){
  bool problem_condition = (argc >= 2) && (std::strcmp(argv[1],"problem") == 0);

  if (problem_condition) 
     cout << "The program will throw an exception during use of resource" << endl;
  else
     cout << "The program will use resource without throwing an exception" << endl;

  try{
    use_resource("sample_resource", problem_condition);
  }
  catch(Problem){
    cout << "Recovering" << endl;
  }

}