RAII Pattern in C++
Level 5444 keystrokes
RAII ties a resource to an object's lifetime: FileHandle "opens" the file in its constructor and "closes" it in its destructor. When the block ends, the destructor runs automatically, before the last line is printed. (The file is only simulated with messages.)
C++ code
// Class that owns a (simulated) file1class FileHandle {2 string filename; // Whether the file is currently open3 bool isOpen;4public: // Acquire the resource in the constructor5 FileHandle(const string& name) : filename(name), isOpen(true) {6 cout << "Opening file: " << filename << endl;7 } // Release it in the destructor, which runs automatically at the end of the scope8 ~FileHandle() { // Closes only if still open9 if (isOpen) {10 cout << "Closing file: " << filename << endl;11 isOpen = false;12 }13 } // Simulated write operation14 void write(const string& data) {15 cout << "Writing: " << data << endl;16 }17};18 // Inner block: file lives only inside these braces19{ // Prints "Opening file: data.txt"20 FileHandle file("data.txt"); // Prints "Writing: Hello RAII"21 file.write("Hello RAII");// End of the block: the destructor prints "Closing file: data.txt"22}// Runs after the file has already been closed23cout << "File automatically closed" << endl;Output
Opening file: data.txt Writing: Hello RAII Closing file: data.txt File automatically closed
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this C++ code and how often they appear.
<× 22"× 12;× 10(× 8)× 8{× 6}× 6:× 5.× 2&× 2