简体   繁体   中英

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* _responseString = new wchar_t[_responseLength];

I get a warning about '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). 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 . You need to static_cast your streamoff value to a size_t.

Note that tellg() may return -1. static_cast ing -1 to size_t will result in a huge positive value; trying to allocate that much memory will cause your program to fail. You need to explicitly check for -1 before casting.

Please do not use naked pointers and 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.

The limitation you get with this is that you cannot read a file bigger than 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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