RAII(Resource Acquisition Is Initialization)


Resource acquisition is initialization (RAII) is a programming idiom used in several object-oriented languages to describe a particular language behavior.

RAII (Resource Acquisition Is Initialization) is one of the famous design patterns.
The technique was developed for exception-safe resource management in C++ during 198489, primarily by Bjarne Stroustrup and Andrew Koenig.

RAII patterns are important techniques for preventing leakage in languages such as C++ that require developers to directly manage resources.


The following C++11 example demonstrates usage of RAII for file access and mutex locking:

#include <fstream>
#include <iostream>
#include <mutex>
#include <stdexcept>
#include <string>
void WriteToFile(const std::string& message) {
  // |mutex| is to protect access to |file| (which is shared across threads).
  static std::mutex mutex;
// Lock |mutex| before accessing |file|.
  std::lock_guard<std::mutex> lock(mutex);
// Try to open file.
  std::ofstream file("example.txt");
  if (!file.is_open()) {
    throw std::runtime_error("unable to open file");
  }
// Write |message| to |file|.
  file << message << std::endl;
// |file| will be closed first when leaving scope (regardless of exception)
  // mutex will be unlocked second (from lock destructor) when leaving scope
  // (regardless of exception).
}



<Ref : https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization>

#RAII #Resource Acquisition Is Initialization #C++ #mutex #Memory leakage #std::auto_ptr

No comments:

Post a Comment

Apartment Buying Guide 2025: Shocking Red Flags You Should NEVER Ignore!

 🏙️ Apartment Buying Guide 2025: Shocking Red Flags You Should NEVER Ignore! 🚨 Are you thinking about buying an apartment in 2025? 🏢  It’...