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::vectorfor 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/destroymethods - 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() 上初始化它
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
