使用向量<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.
相关文章