声明大小为 std::streamoff 的数组

Declaring an array with size std::streamoff

本文关键字:streamoff 数组 std 小为 声明      更新时间:2023-10-16

我有这一行来获取文件大小

std::streamoff _responseLength = _responseIn.tellg();

我正在为wchar_t指针分配内存,

wchar_t* _responseString = new wchar_t[_responseLength];

我收到有关'initializing' : conversion from 'std::streamoff' to 'unsigned int', possible loss of data的警告.

我应该怎么做才能完全消除编译器的警告?

std::streamoff 是一个大的(至少 64 位)有符号整数(通常为 long longint64_t,如果是 64 位,则为 long)。用于表示对象大小以及数组和容器长度的类型是 size_t ,它是无符号的,通常unsigned long 。您需要将流值static_cast为size_t。

请注意,tellg()可能会返回 -1。 static_cast -1 到 size_t 将导致巨大的正值;尝试分配这么多内存将导致程序失败。您需要在强制转换之前显式检查 -1。

请不要使用裸指针和new。如果需要缓冲区,请使用以下命令:

std::vector<wchar_t> buffer(static_cast<size_t>(responseLength));
// use &buffer.front() if you need a pointer to the beginning of the buffer

分配内存的新运算符需要unsigned int,因此std::streamoff将转换为unsigned int以满足要求。

这样做的限制是您无法读取大于 4GB 的文件。

为避免此限制,您需要将文件分成适合内存的片段读取。

如果您的文件只有大约 100MB 大,请忽略警告。