C++ 的 RAII模式
等级 5444 次按键
RAII 把资源与对象的生命周期绑定:FileHandle 在构造函数中“打开”文件,在析构函数中“关闭”文件。代码块结束时析构函数自动执行,早于最后一行的输出。(文件操作只是用消息模拟。)
C++ 代码
// 拥有一个(模拟的)文件的类1class FileHandle {2 string filename; // 文件当前是否打开3 bool isOpen;4public: // 在构造函数中获取资源5 FileHandle(const string& name) : filename(name), isOpen(true) {6 cout << "Opening file: " << filename << endl;7 } // 在析构函数中释放资源,作用域结束时自动调用8 ~FileHandle() { // 只在仍然打开时关闭9 if (isOpen) {10 cout << "Closing file: " << filename << endl;11 isOpen = false;12 }13 } // 模拟的写入操作14 void write(const string& data) {15 cout << "Writing: " << data << endl;16 }17};18 // 内部代码块:file 只在这对花括号内存在19{ // 输出“Opening file: data.txt”20 FileHandle file("data.txt"); // 输出“Writing: Hello RAII”21 file.write("Hello RAII");// 代码块结束:析构函数输出“Closing file: data.txt”22}// 在文件已经关闭之后执行23cout << "File automatically closed" << endl;运行结果
Opening file: data.txt Writing: Hello RAII Closing file: data.txt File automatically closed
可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 C++ 代码中需要输入的符号及其出现次数。
<× 22"× 12;× 10(× 8)× 8{× 6}× 6:× 5.× 2&× 2