1) Is some memory being held up because of capacity? What if i have not
explicitly reserve()'d?
Even if you did not call reserve, the std::string
object can still hold up some memory1 for (even a default constructed) std::string
. And this is true with std::string
implementations that uses Short String Optimization
2)If i use std::reserve() and dont end up using the entire capcity
then am i wasting memory?
It depends on what you mean by wasting memory; std::string
dynamically resizes its buffer to accommodate changes in the size of the string. Well, in the case of Short String Optimized std::string
implementations, there is nothing you can do about it. The memory is in the string object itself.
3)Will this extra memory which i am not using be allocated to
something else, if required?
No. A std::string
object manages the memory it allocated, and it may or may not give it up2 wholly or partly, until its destroyed. See David Schwartz's comment
EDIT: Suppose i have
string a= "something";
Now i edit the string and know that a won't have more than two
characters.So is it wise to call a.reserve(2)
so that memory is not
wasted?
If you modified a
in a way that changes a.size()
, such as calling resize method or assigning it to a new string of length 2, then the proceeding reserve call can2 be beneficial.
Note that, calling reserve would not reduce the string's contents. std::string::reserve
is not permitted to truncate the string. It is only permitted to work on unused memory. If you call std::string::reserve(new_capacity_intended)
with new_capacity_intended
less than the size()
of the string, the best that could possibly happen is the same effect of std::string::shrink_to_fit
.
To reduce the string's memory (if the implementation does a binding shrink_to_fit
request) and shrink it to the first two characters:
string a= "something";
//resize it first
a.resize(2); //or by some assignment such as a = "so";
//then
a.reserve(2); // or better still a.shrink_to_fit();
1: by memory, I assume Virtual Memory
2: std::string::reserve
or std::string::shrink_to_fit
may or may not give up the string's unused memory.