在开始之前,我需要说明我的应用程序使用了很多字符串,这些字符串平均非常小,并且一旦创建就不会改变。
在 Visual Studio 2010 中,我注意到 std::string 的容量至少为 30。即使我写 std::string str = "test";
,str 的容量也是30. 函数 str.shrink_to_fit()
对此没有任何作用,尽管 std::vector 存在同名函数并且按预期工作,即减小容量以使容量 == 大小。
- 为什么
std::string::shrink_to_fit()
不能按预期工作? - 如何确保字符串分配的内存最少?
最佳答案
- 您的
std::string
实现很可能使用某种形式的 short string optimization导致较小字符串的大小固定,对shrink_to_fit
无效.请注意shrink_to_fit
对实现没有约束力,所以这实际上是符合要求的。 - 您可以使用
vector<char>
获得更精确的内存管理,但会丢失std::string
的一些附加功能.你也可以自己写string
使用vector
的包装器内部。
关于c++ - 我可以让 std::string 使用更少的内存吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34634126/