gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:04:25 24 4
gpt4 key购买 nike

使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com