简体   繁体   English

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

[英]Declaring an array with size std::streamoff

I have this line to get file size 我有这行来获取文件大小

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

I am allocating memory for a wchar_t pointer with, 我正在为wchar_t指针分配内存,

wchar_t* _responseString = new wchar_t[_responseLength];

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

What should I do to completely eliminate the warning by the compiler? 我应该怎么做才能完全消除编译器的警告?

std::streamoff is a large (at least 64 bits) signed integer (often long long or int64_t , or long if that is 64 bits). std :: streamoff是一个大的(至少64位)有符号整数(通常为long longint64_t ,如果为64位,则为long )。 The type used to express the size of objects and the length of arrays and containers is size_t , which is unsigned, often unsigned long . 用于表示对象的大小以及数组和容器的长度的类型是size_t ,它是无符号的,通常是无unsigned long You need to static_cast your streamoff value to a size_t. 您需要将流输出值static_cast到size_t。

Note that tellg() may return -1. 请注意, tellg()可能返回-1。 static_cast ing -1 to size_t will result in a huge positive value; static_cast -1 to size_t将产生巨大的正值; trying to allocate that much memory will cause your program to fail. 尝试分配那么多的内存将导致您的程序失败。 You need to explicitly check for -1 before casting. 您需要在投放前明确检查-1。

Please do not use naked pointers and new . 请不要使用裸指针和new If you need a buffer, use the following: 如果需要缓冲区,请使用以下命令:

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

The new operator to allocate memory takes an unsigned int so the std::streamoff gets converted to an unsigned int to fit the requirement. 用于分配内存的新运算符采用unsigned int因此std::streamoff被转换为unsigned int以符合要求。

The limitation you get with this is that you cannot read a file bigger than 4GB. 这样做的限制是,您不能读取大于4GB的文件。

To avoid this limitation, you need to read the file in pieces that fit into memory. 为避免此限制,您需要按适合内存的片段读取文件。

If your file is only about 100MB big, just ignore the warning. 如果您的文件只有大约100MB,请忽略该警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM