raii原则在c++++中通过将资源获取与对象初始化结合,确保资源安全管理。raii的核心是将资源生命周期与对象生命周期绑定,避免资源泄漏。
#include <iostream> #include <fstream> class FileHandler { private: std::fstream file; public: // 构造函数获取资源 FileHandler(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in) : file(filename, mode) { if (!file.is_open()) { throw std::runtime_error("Unable to open file"); } std::cout << "File opened: " << filename << std::endl; } // 析构函数释放资源 ~FileHandler() { if (file.is_open()) { file.close(); std::cout << "File closed" << std::endl; } } // 读取文件内容 std::string readLine() { std::string line; std::getline(file, line); return line; } }; int main() { try { FileHandler file("example.txt"); std::cout << file.readLine() << std::endl; } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; } return 0; }
以上就是什么是C++中的RAII原则?的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号