2014-12-03 54 views
0

我这行获得文件大小声明大小为STD数组:: streamoff

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

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

回答

3

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

请注意,tellg()可能会返回-1。 static_cast ing -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

新的运营商来分配内存需要一个unsigned int所以std::streamoff被转换成unsigned int以适应需求。

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

为避免这种限制,您需要阅读适合内存的文件。

如果你的文件只有100MB大,就忽略警告。