C++
RAII
Resource Acquisition Is Initialization.
By EZ4Code Team
raiiresource-management
Code
#include <iostream>
#include <fstream>
#include <mutex>
// RAII class: acquire on construct, release on destruct
class FileGuard {
FILE* file;
public:
explicit FileGuard(const char* path) {
file = fopen(path, "r");
if (!file) throw std::runtime_error("Cannot open file");
}
~FileGuard() {
if (file) fclose(file);
}
// Disable copy
FileGuard(const FileGuard&) = delete;
FileGuard& operator=(const FileGuard&) = delete;
FILE* get() { return file; }
};
// lock_guard uses RAII
std::mutex mtx;
void safe_increment(int& counter) {
std::lock_guard<std::mutex> lock(mtx);
counter++;
} // Auto unlock
int main() {
{
FileGuard fg("example.txt");
// Use fg.get() to read file
} // fg destructor auto-closes file
{
std::ofstream out("temp.txt");
out << "Hello RAII";
} // Auto close file
return 0;
}Explanation
RAII binds resources to object lifetime, acquiring on construction and releasing on destruction, ensuring exception safety.