RAII
RAII 的工作原理
#include <iostream>
#include <fstream>
class FileHandler {
public:
FileHandler(const char* filename) {
file.open(filename);
if (!file.is_open()) {
throw std::runtime_error("Failed to open file.");
}
}
~FileHandler() {
if (file.is_open()) {
file.close();
std::cout << "File closed automatically in destructor." << std::endl;
}
}
void write(const std::string& data) {
if (file.is_open()) {
file << data;
}
}
private:
std::fstream file;
};
int main() {
try {
FileHandler fileHandler("example.txt");
fileHandler.write("Hello, RAII!");
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
}
// fileHandler 超出作用域,自动调用析构函数释放资源
return 0;
}RAII 的优势
RAII 的局限性
常见的 RAII 示例
Last updated