I declare a variable string s;
and do s = "abc";
now it has buffer of 3 characters.
After
s = "abcd"
it has a buffer of 4 characters.
Now after the third statement
s = "ab"
question is will it keep the buffer of 4 characters or will it reallocate a 2 character buffer?
If it will allocate 2 character buffer is there any way I can tell it to keep the allocated maximum buffer.
So does it keep the buffer of maximum size ever allocated ?
s = "ab"
s="abc"
s="a"
s="abcd"
s="b"
Now it should keep a buffer of size 4.
Is that possible?
The string will keep its buffer once it is allocated, and only reallocate if its needs an even larger buffer. It will also likely start with an initial buffer size larger than 3 or 4.
You can check the allocated size using the capacity()
member function.
After James' comments below I still believe my answer is correct for the examples given in the question.
However, for a reference counted implementation a sequence like this
s = "some rather long string...";
std::string t = "b";
s = t;
would set s.capacity()
to be equal to t.capacity()
if the implementation decides to share the internal buffer between s
and t
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With