c++ - 如何释放字符串未使用的容量

标签 c++ string visual-c++ memory-management

我在我的程序中处理很多字符串。 这些字符串数据在被读入我的程序后的整个生命周期内都不会改变。

但是由于C++字符串预留容量,它们浪费了很多肯定不会被使用的空间。 我试图释放这些空间,但没有用。

下面是我试过的简单代码:

string temp = "1234567890123456";
string str;

cout << str.capacity() << endl;   

str.reserve(16);    
cout << str.capacity() << endl;     
// capacity is 31 on my computer    

str += temp;    
cout << str.capacity() << endl;    

str.reserve(16);    
cout << str.capacity() << endl;     
// can't release. The capacity is still 31.

(编译器为Visual C++)

我怎样才能释放它?

最佳答案

当您调用 reserve 时,您正在发出一个请求 来更改容量。实现将只保证保留一个等于或大于这个数量的数字。 因此,缩减容量的请求可能会被特定实现安全地忽略。

但是,我鼓励您考虑一下这是否不是过早的优化。你确定你真的制作了这么多字符串以至于它对你来说是内存瓶颈吗?您确定瓶颈实际上是内存吗?

来自 reserve 的文档:

This can expand or shrink the size of the storage space in the string, although notice that the resulting capacity after a call to this function is not necessarily equal to res_arg but can be either equal or greater than res_arg, therefore shrinking requests may or may not produce an actual reduction of the allocated space in a particular library implementation. In any case, it never trims the string content (for that purposes, see resize or clear, which modify the content).

关于c++ - 如何释放字符串未使用的容量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/740030/

相关文章:

c++ - 为什么我不能从这个模板函数返回一个引用?

c# - 如何检查两个字符串是否在 C# 中部分匹配?

python - 计算不包括空格的字符数 - python

c++ - 析构函数之前工作。如何?

c++ - 在 .NET 应用程序中包含 NOT .NET cpp 和 h

c - VC:如何在.def文件中指定'unecorate'?

c++ - 将函数及其实现从主文件移动到不同的文件(.hpp 和 .cpp)时,性能会受到很大影响

c++ - 从 std::string 到 unsigned char[] 的转换

c++ - 实现主从

javascript - 如何从元素子元素中获取文本?