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

时间:2014-12-03 08:37:36

标签: c++

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

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的警告。

如何完全消除编译器的警告?

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

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

您遇到的限制是您无法读取大于4GB的文件。

要避免此限制,您需要将文件读入适合内存的文件中。

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

相关问题