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 1984–89,
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.
#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