Devolus
Devolus

Reputation: 22094

When does std::string reallocate memory?

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?

Upvotes: 4

Views: 2467

Answers (3)

John Zwinck
John Zwinck

Reputation: 249642

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.

Upvotes: 4

Steve Jessop
Steve Jessop

Reputation: 279455

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.

Upvotes: 1

Paul Evans
Paul Evans

Reputation: 27577

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.

Upvotes: 0

Related Questions