c++ - 使用 C++ 和 RAII 读取文件

标签 c++ raii

使用 C++ 和 RAII 读取文件的最佳方式是什么?我见过的所有示例都使用类似于以下代码的内容:

#include <iostream>
#include <fstream>

int main () {

  std::ifstream is ("test.txt", std::ifstream::binary);
  if (is) {
    is.seekg (0, is.end);
    int length = is.tellg();
    is.seekg (0, is.beg);

    char * buffer = new char [length]; // Seems wrong?

    is.read (buffer, length);

    delete[] buffer;
  }
}

根据我对 RAII 的了解,初始化 char 指针并手动删除它似乎是错误的。

我做过类似的事情:

#include <iostream>
#include <fstream>

int main () {

  std::ifstream is ("test.txt", std::ifstream::binary);
  if (is) {
    is.seekg (0, is.end);
    int length = is.tellg();
    is.seekg (0, is.beg);

    std::shared_ptr<char> buffer = std::make_shared<char>();

    is.read (buffer.get(), length);
  }
}

但我也不确定这是否正确。我也无法成功转换 std::shared_ptr<char>std::shared_ptr<uint8_t>如果需要(或者是否可能,或者是否有意义?)。

最佳答案

char * buffer = new char [length]; // Seems wrong?

没有错,只是……不安全。

更安全的实现:

std::unique_ptr<char[]> buffer{new char [length]}; // note: use char[] as parameter
is.read (buffer.get(), length);

比以前更好:

std::vector<char> buffer{length, ' '};
is.read (buffer.data(), length);

或:

std::string buffer{length, ' '};
is.read (buffer.data(), length);

特别是,这是未定义的行为:

std::shared_ptr<char> buffer = std::make_shared<char>();
is.read (buffer, length);

因为它动态分配 一个 个字符,然后在该内存位置放置最多 length 个字符。实际上,这是一个缓冲区溢出,除非你的长度总是 1。

关于c++ - 使用 C++ 和 RAII 读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23989308/

相关文章:

c++ - Windows 安装程序,在 C++ 中的自定义操作中访问自定义属性

C++ 和 XGrabKeyboard 键盘锁定

c++ - 在编译时检查模板参数是否是一种字符串

c++ - 正确终止程序。使用异常

C++ 优化器删除具有副作用的对象

c++ - 在 Windows 7 中录制您所听到的音频

c++ - 列出 Win32 设备命名空间的内容

python - Python 中的 RAII - 离开作用域时自动销毁

rust - 如何测试RAII?

c++11 - 移动构造函数和 const 成员变量