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

前端之家收集整理的这篇文章主要介绍了c – 如何释放字符串的未使用容量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在程序中处理了很多字符串.
这些字符串数据在读入我的程序后不会在整个生命周期内发生变化.

但是由于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)

我该怎么发布呢?

解决方法

当您拨打预订时,您正在请求更改容量.实现仅保证保留等于或大于此数量的数字.因此,特定实现可以安全地忽略缩小容量的请求.

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

从保留文件

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).

原文链接:https://www.f2er.com/c/117645.html

猜你在找的C&C++相关文章