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

  • Kubernetes for Developers

    Microsoft's Dan Wahlin previews his introductory "Kubernetes for Developers" session at Visual Studio Live! San Diego 2026, explaining how developers can get past the Kubernetes learning curve by starting locally, mastering Pods first, and using Services to make containerized applications reliably accessible.

  • VS Code Keeps Eye on Costs in v1.126 Update

    Visual Studio Code 1.126 adds session-level Copilot cost information, continuing Microsoft's recent focus on helping developers monitor and manage usage-based GitHub Copilot billing.

  • Open VSX 1.0.0 Puts Focus on Open Extension Registry for VS Code Ecosystem

    Eclipse Open VSX has reached 1.0.0, highlighting its role as a vendor-neutral registry for VS Code-compatible extensions.

  • Infragistics Puts MCP Toolchain at Center of Ultimate 26.1

    Infragistics Ultimate 26.1 introduces the Ignite UI Enterprise MCP toolchain for AI-assisted app development across Angular, React, Web Components and Blazor.

Subscribe on YouTube