Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
#include <iostream> #include <fstream> #include <stdexcept> // RAII file wrapper class FileHandle { public: explicit FileHandle(const char* path, const char* mode) { file_ = std::fopen(path, mode); if (!file_) throw std::runtime_error("Cannot open file"); std::cout << "File opened "; } ~FileHandle() { if (file_) { std::fclose(file_); std::cout << "File closed "; // always runs } } // Prevent copy FileHandle(const FileHandle&) = delete; FileHandle& operator=(const FileHandle&) = delete; FILE* get() const { return file_; } private: FILE* file_; }; // RAII mutex simulation struct MutexLock { explicit MutexLock(bool& mutex) : mutex_(mutex) { mutex_ = true; std::cout << "Lock acquired "; } ~MutexLock() { mutex_ = false; std::cout << "Lock released "; } bool& mutex_; }; int main() { bool mutex = false; { MutexLock lock(mutex); std::cout << "Critical section "; // lock released automatically at end of block } // FileHandle example (file may not exist in demo) try { FileHandle fh("demo.txt", "w"); std::fputs("Hello RAII ", fh.get()); // file closed automatically even if exception thrown } catch (const std::exception& e) { std::cout << "Error: " << e.what() << " "; } return 0; }
Result
Open