std::string 何时重新分配内存? [英] When does std::string reallocate memory?

查看:69
本文介绍了std::string 何时重新分配内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用 std::string 对象并且我想向它添加字符时,它会预先分配一些内存,还是只分配我需要的内存?

When using an std::string object and I want to add characters to it, would it preallocate some memory, or would it only allocate as much as I need?

准确地说:

 std::string s;
 s.reserve(20);
 char c = 'a';
 s = "";
 for(int i = 0; i < 25; i++)
    s += c;

在上面的例子中,我保留了一定数量的内存.现在当我清除字符串时,会不会导致保留的内存被丢弃?在循环中它会填满保留的内存,然后每次重新分配额外的 5 个字符吗?

In the above example I reserve an amount of memory. Now when I clear the string, will it cause the reserved memory to be discarded? In the loop would it fill up the reserved memory and then reallocate for the extra 5 characters each time?

推荐答案

没有要求 std::string 在为它分配空字符串时释放分配的内存.当您为它分配一个短字符串时也不会.唯一的要求是,当它分配内存来容纳更大的字符串时,分配必须以实现摊销恒定时间的方式进行.一个简单的实现是每次需要更多空间时增长 2 倍.

There is no requirement that std::string release allocated memory when you assign an empty string to it. Nor when you assign a short string to it. The only requirement is that when it allocates memory to hold a larger string, the allocation must be done in a way that achieves amortized constant time. A simple implementation would be to grow by a factor of 2 each time more space is needed.

如果你想最小化字符串的容量,你可以在 C++11 中使用 string::shrink_to_fit().在 C++11 之前,有些人在需要减少容量时会使用交换技巧".

If you want the string's capacity to be minimized, you can use string::shrink_to_fit() in C++11. Before C++11 some people resorted to the "swap trick" when they needed to reduce capacity.

这篇关于std::string 何时重新分配内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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