Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++ raii

作者:暗夜骑士   发布日期:2025-02-20   浏览:89

#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++ 日志库

大家都在看

c++闭包

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++freopen怎么用

c++ 获取系统时间

c++进制转换函数

c++ tcp

c++ gcd函数

c++ cli

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站