问题
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, reserve
d memory isn't discarded, swap
with 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