Using vectorlt;chargt; as a buffer without initializing it on resize()(使用向量char作为缓冲区而不在 resize() 上初始化它)
问题描述
我想使用 vector
作为缓冲区.该界面非常适合我的需求,但在将其调整为超出当前大小时会降低性能,因为内存已初始化.我不需要初始化,因为在任何情况下数据都会被某些第三方 C 函数覆盖.有没有办法或特定的分配器来避免初始化步骤?请注意,我确实想使用 resize()
,而不是像 reserve()
和 capacity()
之类的其他技巧,因为我需要 size()
始终表示我的缓冲区"的有效大小,而 capacity()
在 resize()
之后可能大于其大小>,所以,我不能依赖 capacity()
作为我的应用程序的重要信息.此外,向量的(新)大小永远不会提前知道,所以我不能使用 std::array
.如果无法以这种方式配置矢量,我想知道我可以使用哪种容器或分配器来代替 vector
.唯一的要求是,vector 的替代方案最多必须基于 STL 或 Boost.我可以访问 C++11.
I want to use vector<char>
as a buffer. The interface is perfect for my needs, but there's a performance penalty when resizing it beyond its current size, since the memory is initialized. I don't need the initialization, since the data will be overwritten in any case by some third-party C functions. Is there a way or a specific allocator to avoid the initialization step? Note that I do want to use resize()
, not other tricks like reserve()
and capacity()
, because I need size()
to always represent the significative size of my "buffer" at any moment, while capacity()
might be greater than its size after a resize()
, so, again, I cannot rely on capacity()
as a significative information for my application. Furthemore, the (new) size of the vector is never known in advance, so I cannot use std::array
. If vector cannot be configured that way, I'd like to know what kind of container or allocator I could use instead of vector<char, std::alloc>
. The only requirement is that the alternative to vector must at most be based on STL or Boost. I have access to C++11.
推荐答案
标准库中没有任何内容可以满足您的要求,我也不知道 boost 中的任何内容.
There's nothing in the standard library that meets your requirements, and nothing I know of in boost either.
我能想到三个合理的选择:
There are three reasonable options I can think of:
- 暂时坚持使用
std::vector
,在代码中留下注释,如果这会导致您的应用程序出现瓶颈,请返回. - 使用带有空
construct
/destroy
方法的自定义分配器 - 并希望您的优化器足够聪明以删除对它们的任何调用. - 围绕动态分配的数组创建一个包装器,仅实现您需要的最少功能.
- Stick with
std::vector
for now, leave a comment in the code and come back to it if this ever causes a bottleneck in your application. - Use a custom allocator with empty
construct
/destroy
methods - and hope your optimiser will be smart enough to remove any calls to them. - Create a wrapper around a a dynamically allocated array, implementing only the minimal functionality that you require.
这篇关于使用向量<char>作为缓冲区而不在 resize() 上初始化它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用向量<char>作为缓冲区而不在 resize() 上初始化它
基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01