When does std::string reallocate memory?

元气小坏坏 提交于 2020-01-14 12:57:10

问题


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?

To be precise:

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

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?


回答1:


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.

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.




回答2:


string doesn't "remember" that you said 20 characters, it just knows its current capacity. So your reserve(20) call increases the capacity to at least 20 and has no further effect.

When you add 25 characters to the string, the capacity increases to at least 25 along the way. Then it remains at this new level unless you do something that reduces the capacity. Calling clear() does not alter the capacity.




回答3:


No, reserved memory isn't discarded, swapwith an empty object for that.

Yes, when your reserve space is full, the next append, etc will cause a reallocation.



来源:https://stackoverflow.com/questions/25974085/when-does-stdstring-reallocate-memory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!