When does std :: string reallocate memory?

When using an object std::string

and I want to add symbols to it, will it allocate some memory, or will it 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 example above, I reserve the amount of memory. Now when I clear the line, will it discard the reserved memory? In a loop, will it fill the reserved memory and then reallocate for an extra 5 characters each time?

+3


source to share


3 answers


It is not required to std::string

free allocated memory when assigning an empty string to it. Also when you assign a short string to it. The only requirement is that when it allocates memory to store a larger row, the allocation must be done in such a way as to ensure constant amortization time. A simple implementation will grow 2x every time more space is needed.



If you want to minimize the size of a string, you can use it string::shrink_to_fit()

in C ++ 11. Before C ++ 11, some people used the "swap trick" when they needed to reduce capacity.

+3


source


string

doesn't "remember" what you said 20 characters, it just knows its current capacity. So your call reserve(20)

increases the capacity by at least 20 and has no effect.



When you add 25 characters to a string, the capacity increases to at least 25. It then stays at this new level unless you do something that lowers the capacity. The call clear()

does not change capacity.

+1


source


No, reserve

d memory is not discarded, swap

with an empty object for that.

Yes, when your space is reserve

full, next append

, etc. will lead to redistribution.

0


source







All Articles