c++ - 我可以让 std::string 使用更少的内存吗?

标签 c++ string visual-studio-2010 memory

在开始之前,我需要说明我的应用程序使用了很多字符串,这些字符串平均非常小,并且一旦创建就不会改变。

在 Visual Studio 2010 中,我注意到 std::string 的容量至少为 30。即使我写 std::string str = "test";,str 的容量也是30. 函数 str.shrink_to_fit() 对此没有任何作用,尽管 std::vector 存在同名函数并且按预期工作,即减小容量以使容量 == 大小。

  1. 为什么 std::string::shrink_to_fit() 不能按预期工作?
  2. 如何确保字符串分配的内存最少?

最佳答案

  1. 您的std::string实现很可能使用某种形式的 short string optimization导致较小字符串的大小固定,对 shrink_to_fit 无效.请注意 shrink_to_fit对实现没有约束力,所以这实际上是符合要求的。
  2. 您可以使用 vector<char>获得更精确的内存管理,但会丢失 std::string 的一些附加功能.你也可以自己写string使用 vector 的包装器内部。

关于c++ - 我可以让 std::string 使用更少的内存吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34634126/

相关文章:

c++ - 如何为 Internet Explorer 创建扩展作为 Exe Com 服务器?

c - Microsoft Visual C++ Express 中的 Lotus C API 示例

c++ - SendInput() 不等于在 C++ 中手动在键盘上按键?

c++ - C++ 放置的多个参数 new 'constructor'

c++ - 在 TreeView C++ BUILDER 中突出显示项目

.net - 从网络共享运行(本地)Azure 辅助角色

c++ - 使用 Howard Hinnant 的 date.h 计算某个日期今年的天数

java - 将字符串拆分为几个两个字符串

javascript - 如何在没有正则表达式的情况下检查数组中的单词是否包含在字符串中?

python - python中的模板