声明大小为 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
的警告.
我应该怎么做才能完全消除编译器的警告?
std::streamoff 是一个大的(至少 64 位)有符号整数(通常为 long long
或 int64_t
,如果是 64 位,则为 long
)。用于表示对象大小以及数组和容器长度的类型是 size_t
,它是无符号的,通常unsigned long
。您需要将流值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
分配内存的新运算符需要unsigned int
,因此std::streamoff
将转换为unsigned int
以满足要求。
这样做的限制是您无法读取大于 4GB 的文件。
为避免此限制,您需要将文件分成适合内存的片段读取。
如果您的文件只有大约 100MB 大,请忽略警告。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '