如何释放字符串的未使用容量 [英] How to release the unused capacity of a string

查看:59
本文介绍了如何释放字符串的未使用容量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am dealing with a lot of strings in my program. These string data don't change through out the whole life time after they being read into my program.

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

But since the C++ string reserves capacity, they waste a lot of space that won't be used for sure. I tried to release those spaces, but it didn't work.

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

The following is the simple code that I tried:

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

(The compiler is Visual C++)

我怎样才能释放它?

推荐答案

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

When you call reserve, you're making a request to change the capacity. Implementations will only guarantee that a number equal to or greater than this amount is reserved. Therefore, a request to shrink capacity may be safely ignored by a particular implementation.

但是,我鼓励您考虑这是否不是过早的优化.您确定您真的制作了如此多的字符串,以至于这对您来说是一个内存瓶颈吗?您确定真正的瓶颈是内存吗?

However, I encourage you to consider whether this isn't premature optimization. Are you sure that you're really making so many strings that it's a memory bottleneck for you? Are you sure that it's actually memory that's the bottleneck?

来自 reserve 的文档:

这可以扩大或缩小字符串中的存储空间,虽然注意到结果调用此函数后的容量不一定等于 res_arg但可以等于或大于比 res_arg,因此缩小请求可能会也可能不会产生实际减少的分配特定图书馆的空间执行.无论如何,它永远不会修剪字符串内容(为此目的,请参阅调整大小或清除,其中修改内容).

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

这篇关于如何释放字符串的未使用容量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆