本帖最后由 小小蚂蚁举千斤 于 2024-3-28 19:28 编辑
在文件操作中,使用RAII可以有效地管理文件资源的获取和释放,避免忘记关闭文件或异常时未能正确释放资源的问题。
- #include <iostream>
- #include <fstream>
- class File {
- public:
- File(const std::string& filename) : file(filename) {
- if (!file.is_open()) {
- throw std::runtime_error("Failed to open file: " + filename);
- }
- }
- ~File() {
- if (file.is_open()) {
- file.close();
- }
- }
- void write(const std::string& data) {
- file << data;
- }
- private:
- std::ofstream file;
- };
- int main() {
- try {
- File myfile("example.txt");
- myfile.write("Hello, RAII!");
- } catch (const std::exception& e) {
- std::cout << e.what() << std::endl;
- }
- return 0;
- }
|