gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 18:42:07 27 4
gpt4 key购买 nike

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

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com