Back to notes -- Keyboard shortcut: 'u'  previous -- Keyboard shortcut: 'p'  next -- Keyboard shortcut: 'n'  Slide program -- Keyboard shortcut: 't'    A class Resource and its application in the function use_resource - compilable version.Lecture 3 - slide 11 : 36
Program 2
// A complete version that can be used to illustrate what happens in case of exceptions after resource allocation. 
// This version reveals the resource allocation and deallocation on standard output. 

#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 and 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;
  }

}