繁体   English   中英

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

[英]Declaring an array with size 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的警告'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 to 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,请忽略该警告。

暂无
暂无

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

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