#include <iostream>
#include <fstream>
class FileHandler {
public:
// 构造函数,打开文件
FileHandler(const char* filename, const char* mode)
: file_(fopen(filename, mode)) {
if (!file_) {
throw std::runtime_error("Failed to open file");
}
}
// 析构函数,关闭文件
~FileHandler() {
if (file_) {
fclose(file_);
}
}
// 禁用拷贝构造和赋值操作
FileHandler(const FileHandler&) = delete;
FileHandler& operator=(const FileHandler&) = delete;
// 移动构造函数
FileHandler(FileHandler&& other) noexcept
: file_(other.file_) {
other.file_ = nullptr;
}
// 移动赋值操作符
FileHandler& operator=(FileHandler&& other) noexcept {
if (this != &other) {
if (file_) {
fclose(file_);
}
file_ = other.file_;
other.file_ = nullptr;
}
return *this;
}
// 读取文件内容
void readFile() {
if (file_) {
char buffer[1024];
while (fgets(buffer, sizeof(buffer), file_) != nullptr) {
std::cout << buffer;
}
}
}
private:
FILE* file_;
};
int main() {
try {
FileHandler handler("example.txt", "r");
handler.readFile();
} catch (const std::exception& e) {
std::cerr << e.what() << '\n';
}
return 0;
}
这段代码展示了 C++ 中 RAII(Resource Acquisition Is Initialization)的使用。RAII 是一种资源管理技术,确保资源在对象生命周期内正确分配和释放。
FileHandler
对象时,打开文件。如果文件无法打开,则抛出异常。FileHandler
对象销毁时,自动关闭文件,确保资源被正确释放。通过这种方式,RAII 确保了文件资源的安全管理和自动清理,避免了内存泄漏和其他潜在问题。
上一篇:c++queue
下一篇:c++ 日志库
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站