Resource Management in C++: Listing 5

A mediator resource_access_object applying the RAII idiom.

// resource_access_object.hpp
#include <memory>
#include "shared_resource.hpp"

// RAII-styled object to handle access to the shared resource
class resource_access_object {
public:
  resource_access_object();

  // no copy constructor: either use same object or create new.
  resource_access_object(const resource_access_object&) = delete;

  ~resource_access_object();

  void do_alpha();
  void do_beta();
private:
  std::unique_ptr<shared_resource> resource_;
};


// resource_access_object.cpp
#include "resource_access_object.hpp"

resource_access_object() : resource_{create_resource()}
{
  cout << "RAII over resource " << resource_->id << " built.\n";
}

~resource_access_object() {
  // a call to shut_suffices here. As resource_ is a unique_ptr, will
  // free its pointer.
  shut_resource(resource_.get());
  cout << "RAII over resource " << resource_->id << " destroyed.\n";
}

void do_alpha()
{
  cout << "RAII over resource " << resource_->id << " doing <alpha>.\n";
  do_alpha_with_resource(resource_.get());
}

void do_beta()
{
  cout << "RAII over resource " << resource_->id << " doing <beta>.\n";
  do_beta_with_resource(resource_.get());
}

About the Author

Diego Dagum is a software architect and developer with more than 20 years of experience. He can be reached at [email protected].

comments powered by Disqus

Featured

Subscribe on YouTube